Simplest way to parse this XML in Java?

我的未来我决定 提交于 2019-12-11 11:47:52

问题


I have the following XML:

     <ConfigGroup Name="Replication">
        <ValueInteger Name="ResponseTimeout">10</ValueInteger>
        <ValueInteger Name="PingTimeout">2</ValueInteger>
        <ValueInteger Name="ConnectionTimeout">10</ValueInteger>
        <ConfigGroup Name="Pool">
            <ConfigGroup Name="1">
                <ValueString Encrypted="false" Name="Host">10.20.30.40</ValueString>
                <ValueInteger Name="CacheReplicationPort">8899</ValueInteger>
                <ValueInteger Name="RadiusPort">12050</ValueInteger>
                <ValueInteger Name="OtherPort">4868</ValueInteger>
            </ConfigGroup>
            <ConfigGroup Name="2">
                <ValueString Encrypted="false" Name="Host">10.20.30.50</ValueString>
                <ValueInteger Name="CacheReplicationPort">8899</ValueInteger>
                <ValueInteger Name="RadiusPort">12050</ValueInteger>
                <ValueInteger Name="OtherPort">4868</ValueInteger>
            </ConfigGroup>
        </ConfigGroup>
     </ConfigGroup>

I just wondering what is the simplest way to parse this XML in Java - I want the value from the two host elements (e.g. 10.20.30.40 and 10.20.30.50). Note there may be more than two pool entries (or none at all).

I'm having trouble finding a simple example of how to use the various XML parsers for Java.

Any help is much appreciated.

Thanks!


回答1:


The simplest way to search for what you are looking for, would be XPath.

try {

    //Load the XML File
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document configuration = builder.parse("configs.xml");

    //Create an XPath expression
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    XPathExpression expr = xpath.compile("//ConfigGroup/ValueString[@Name='Host']/text()");

    //Execute the XPath query
    Object result = expr.evaluate(configuration, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;

    //Parse the results
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i).getNodeValue()); 
    }
} catch (ParserConfigurationException e) {
    System.out.println("Bad parser configuration");
    e.printStackTrace();
} catch (SAXException e) {
    System.out.println("SAX error loading the file.");
    e.printStackTrace();
} catch (XPathExpressionException e) {
    System.out.println("Bad XPath Expression");
    e.printStackTrace();
} catch (IOException e) {
    System.out.println("IO Error reading the file.");
    e.printStackTrace();
}

The XPath expression

"//ConfigGroup/ValueString[@Name='Host']/text()"

looks for ConfigGroup elements anywhere in your XML, then finds ValueString elements within the ConfigGroup elements, that have a Name attribute with the value "Host". @Name=Host is like a filter for elements with the name ValueString. And text() at the end, returns the text node of the selected elements.




回答2:


Java XPath API allows to do it easily. The following xpath expression

//ValueString[@Name='Host']

should match what you want. Here is how to use it with the API :

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(yourXml.getBytes());
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xpath.compile("//ValueString[@Name='Host']").evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
  String ip = ((Element) nodeList.item(i)).getTextContent();
  // do something with your ip
}



回答3:


File file = new File("some/path");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
NodeList list = document.getElementsByTagName("name/of /your/ element");
// its return NodeList of all descendant Elements with a given tag name, in document order.  
for (int i = 0; i < list .getLength(); i++) {
     System.out.println(list.item(i).getNodeName()+" = "+list.item(i).getNodeValue());
 }



回答4:


You could use SAXON

String vs_source = "Z:/Code_JavaDOCX/1.xml";
Processor proc = new Processor(false);
net.sf.saxon.s9api.DocumentBuilder builder = proc.newDocumentBuilder();
XPathCompiler xpc = proc.newXPathCompiler();
try{
            XPathSelector selector = xpc.compile("//output").load();
            selector.setContextItem(builder.build(new File(vs_source)));
            for (XdmItem item: selector) 
                {
                    System.out.println(item.getStringValue());
                }
        }   
catch(Exception e)
        {
            e.printStackTrace();
        }


来源:https://stackoverflow.com/questions/11720999/simplest-way-to-parse-this-xml-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!