Jump to content

How to regex search tags in XML file


ethan.whitt

Recommended Posts

Hello,

 

I have large batch of unique XML files.  I need to regex match any tag that contains "error" or "drop" within the file.  Once matched, I then need to extract the value and verify that it equals zero.  If the value is not zero, I then need to print the tag name and value.  Any help would be appreciated.

 

Thanks!

 

~ew

Link to comment
https://forums.phpfreaks.com/topic/197299-how-to-regex-search-tags-in-xml-file/
Share on other sites

The XML file is an output of counters and their respective values.  Since the counters can be in different levels within the file, I need to recursively look through all levels.  If a tag is found with "error | runt | whatever" and the counter value _IS_ zero or non-numeric, ignore it.  If the counter value is greater than 1, then only display that tag, regardless of the levels above and it's value.

 

I have been looking for an xpath function that will do this, but so far, no luck.  I think the terms I am using in Google are simply wrong. 

 

I have been looking for an xpath function that will do this, but so far, no luck.

 

One such XPath query could look like:

 

    //*[contains(local-name(), "error") and . > 0]

 

The above asks for all nodes whose tag name contains the word "error" and has a numeric value greater than zero.  Note that in the sample XML document provided, none of the nodes match that criteria.

 

Here's a quickie example script using that query and printing the matching nodes out.

 

<?php

// Load XML file
$xml = new SimpleXMLElement('example_data.txt', NULL, TRUE);

// Search for non-zero errors without child nodes
$errors = $xml->xpath('//*[contains(local-name(), "error") and . > 0]');

// Print out those errors
printf("Found %d errors" . PHP_EOL, count($errors));
foreach ($errors as $error) {
echo $error->saveXML() . PHP_EOL;
}

?>

 

Salathe,

 

Thanks!  This was enlightening.  I can not figure out how to display the tag to each non-zero match.  Say you had this xml as the source file.

 

<a>
     <b>
          <test-error>19</test-error>
     </b>
</b>

 

How would you enable this result?

 

Found 1 errors

test-error 19

 

Thanks!

 

~ew

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.