【问题标题】:Simplest way to parse this XML in Java?用 Java 解析这个 XML 的最简单方法是什么?
【发布时间】:2012-07-28 02:11:43
【问题描述】:

我有以下 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)。请注意,池条目可能超过两个(或根本没有)。

我很难找到一个简单的例子来说明如何为 Java 使用各种 XML 解析器。

非常感谢任何帮助。

谢谢!

【问题讨论】:

标签: java xml dom xml-parsing sax


【解决方案1】:

搜索您要查找的内容的最简单方法是 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 元素中查找 ValueString 元素,这些元素的 Name 属性值为“Host”。 @Name=Host 类似于名称为 ValueString 的元素的过滤器。最后的 text() ,返回被选元素的文本节点。

【讨论】:

    【解决方案2】:

    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
    }
    

    【讨论】:

      【解决方案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】:

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

        【讨论】:

          猜你喜欢
          • 2011-10-03
          • 1970-01-01
          • 2014-05-17
          • 1970-01-01
          • 2023-03-17
          • 1970-01-01
          • 2010-10-28
          • 1970-01-01
          • 2017-07-23
          相关资源
          最近更新 更多