开发者

read multiple name value pair from xml tag

I have an xml tag where it has multiple name and value pairs

here is my xml tag from my file

<AsyncLogger name="org.mule.service.ht开发者_运维技巧tp" level="WARN"/>

using below command to read

  1. AsyncLogger name and its value
  2. log level and its value
cat log4j2.xml | perl -e 'while (<>) { next if (/<!--.*-->/);if (/<!--/) { while (<>) {last if (/-->/) }}else {print "$_"; }} ' | xmllint --format -| grep org.mule.service.http|awk -F'=' '{print $2,$4}'

this is what it is printing

"org.mule.service.http" level

Expecting output with comma separated

org.mule.service.http,WARN


Using xpath with concat() and string() functions:

$ xpath -q -e 'concat(string(//AsyncLogger/@name), ",", string(//AsyncLogger/@level))' file.xml
org.mule.service.http,WARN


Like this using xpath query:

$ xmlstarlet sel -t -v 'concat(//AsyncLogger/@name, ",", //AsyncLogger/@level)' file.xml
org.mule.service.http,WARN
$ xmllint --xpath 'concat(//AsyncLogger/@name, ",", //AsyncLogger/@level)' /tmp/file.xml
org.mule.service.http,WARN 


No wonder there are issues when going to XML with regex. Why not use a library?

perl -MXML::LibXML -wnE'
    $xml = XML::LibXML->load_xml(string => $_); 
    for ( $xml->findnodes("//*") ) {
        @attr = $_->attributes; 
        say for @attr
    }
' file.xml

On the string shown in the question in the file file.xml this prints

 name="org.mule.service.http"
 level="WARN"

This is a demo since I'm not sure what the input is like and what output is needed.

If you indeed just need comma-separated values for each node

perl -MXML::LibXML -wnE'
    $xml = XML::LibXML->load_xml(string => $_); 
    for ( $xml->findnodes("//*") ) { 
        say join ",", map { $_->nodeValue } $_->attributes
    }
' file.xml

This prints

org.mule.service.http,WARN

Browse methods of use in XML::LibXML::Node, a base class of XML::LibXML nodes.

While this can be condensed further it is already getting obscure. Please clarify as suitable.

The code can also be simplified on the account of the input seemingly being mere snippets with a single node. On the other hand, I'd rather recommend putting this in a file and then it will be far nicer and more flexible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜