开发者

Display tag name and value in an xml file in java/unix

I have a questio开发者_JAVA百科n, let's say I have an xml string such as the one below:

< request>SayHello< /request>< response>Wave< /response>

If I want the output to be:

Request: SayHello Response: Wave

How would I proceed? I'm not looking for anything specific I just want to "format" the xml.

Thanks in advance


One way with perl and regexes:

echo "<Request>SayHello</Request><Response>Wave</Response>" | perl -ne 'print "Request: $1 Response: $2\n" if /<Request>(.*?)<\/Request><Response>(.*?)<\/Response>/'

EDIT:

Ok and a bit more generic to catch and print any tags (put in file x.pl):

#!/usr/bin/perl -w

while (<STDIN>) {
    while ($_ =~ /<(.*?)>(.*?)<\/\1>/g) {
        print ($1 . ": " .  $2 . "\n");
    }   
}

Usage example would be:

echo "<Request>Hello</Request><Response>Goodbye</Response><Other>Foo</Other>"|./x.pl

EDIT2:

And then here's another way with java where you can pull out whatever you want based on an xpath expression:

import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;

public class Example {
    Example(String xml) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = dbf.newDocumentBuilder();
        Document doc = builder.parse(xml);

        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpresion expr = xpath.compile("/some/xml/path/text()");
        NodeList nl = (NodeList) xpath.evaluate(doc, XPathConstants.NODE_LIST);

        System.out.println("Node value: " + nl.items(0).getNodeValue());
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜