繁体   English   中英

用Java解析此XML的最简单方法?

[英]Simplest way to parse this XML in Java?

我有以下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>

我只是想知道用Java解析XML的最简单方法是什么-我想要两个宿主元素(例如10.20.30.40和10.20.30.50)中的值。 请注意,可能有两个以上的池条目(或根本没有)。

我很难找到一个简单的示例,说明如何将各种XML解析器用于Java。

任何帮助深表感谢。

谢谢!

Java XPath API可以轻松做到这一点。 以下xpath表达式

//ValueString[@Name='Host']

应该符合您的需求。 这是与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
}

搜索所需内容的最简单方法是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();
}

XPath表达式

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

在XML的任何位置查找ConfigGroup元素,然后在ConfigGroup元素中找到具有Name属性且值为“ Host”的ValueString元素。 @ Name = Host就像一个过滤器,过滤名称为ValueString的元素。 最后的text()返回所选元素的文本节点。

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());
 }

您可以使用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();
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM