JAVA XML:获取内容节点

问题描述 投票:0回答:1

我有这样的xml:

<root>
   <countries>
      <country id="98" nom="Espagne"/>
      <country id="76" nom="France"/>
   </countries>
</root>

我可以用这个来读取根标记:

Document doc = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder().parse(XmlFile);

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());      

Node NodeCountries = doc.getElementsByTagName("countries").item(0);     

System.out.println(nodeToString(NodeCountries));


private static String nodeToString(Node node) throws Exception{
            StringWriter sw = new StringWriter();

              Transformer t = TransformerFactory.newInstance().newTransformer();
              t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
              t.setOutputProperty(OutputKeys.INDENT, "yes");
              t.transform(new DOMSource(node), new StreamResult(sw));

            return sw.toString();
          }

但是我无法获得像这样的国家标签内的所有内容:

<country id="98" nom="Espagne"/>
<country id="76" nom="France"/>
java xml w3c
1个回答
0
投票
以下示例将打印<country id="98" nom="Espagne"/><country id="76" nom="France"/>

import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.InputSource; import java.io.StringReader; import org.w3c.dom.Document; import org.xml.sax.SAXException; ... String xml = "<root><countries><country id=\"98\" nom=\"Espagne\"/><country id=\"76\" nom=\"France\"/></countries></root>"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(xml)); Document doc = builder.parse(is); Node node = doc.getElementsByTagName("countries").item(0); String innerXml = getInnerXml(node); System.out.println(innerXml);

并且辅助方法getInnerXml(node)看起来像这样:

private String getInnerXml(Node node) { DOMImplementationLS lsImpl = (DOMImplementationLS) node.getOwnerDocument().getImplementation().getFeature("LS", "3.0"); LSSerializer lsSerializer = lsImpl.createLSSerializer(); lsSerializer.getDomConfig().setParameter("xml-declaration", false); NodeList childNodes = node.getChildNodes(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < childNodes.getLength(); i++) { sb.append(lsSerializer.writeToString(childNodes.item(i))); } return sb.toString(); }

让我知道我是否误解了要求(再次!)。

<< [[[warning]这不是一个很好的解决方案。它涉及“手工”构造XML(即字符串连接),并且如果输入出乎意料的不同或复杂,则会带来结果易碎甚至损坏的风险。

© www.soinside.com 2019 - 2024. All rights reserved.