【问题标题】:How to ignore the parent node of an XML file in Java如何在 Java 中忽略 XML 文件的父节点
【发布时间】:2015-12-03 18:01:00
【问题描述】:

这是我的 XML 文件

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<hierarchy rotation="0">
    <node class="A">
        <node class="B"/>
        <node class="C"/>
        <node class="D"/>
    </node>
</hierarchy>

谁能告诉我java代码忽略class="A"的节点?我只想要以/&gt; 结尾的子节点并读取它们的属性值。我在java中使用DocumentBuilderFactory类来实现上述场景。

【问题讨论】:

  • 只考虑那些没有子元素的元素。
  • 但我什至尝试过 (!(nodeObject.hasChildNodes())) 但它不起作用

标签: java xml nodes


【解决方案1】:

这样就可以了:

public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
    final String xmlString = "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>"
    + "<hierarchy rotation=\"0\">"
    + "<node class=\"A\">"
    + "<node class=\"B\"/>"
    + "<node class=\"C\"/>"
    + "<node class=\"D\"/>"
    + "</node>"
    + "</hierarchy>";

    final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    final InputSource inputSource = new InputSource(new StringReader(xmlString));
    final Document document = documentBuilder.parse(inputSource);
    final NodeList childNodes = document.getFirstChild().getFirstChild().getChildNodes();

    for (int i = 0; i < childNodes.getLength(); i++) {
        final Node childNode = childNodes.item(i);
        System.out.println("childNode[" + i + "].getAttributes(): " + toStringAttributes(childNode));
    }
}

private static String toStringAttributes(Node childNode) {
    String attributesString = "[";
    final NamedNodeMap attributes = childNode.getAttributes();

    for (int i = 0; i < attributes.getLength(); i++) {
        final Node node = attributes.item(i);
        attributesString += node.getNodeName();
        attributesString += "=";
        attributesString += "\"" + node.getNodeValue() + "\"";
        if (i < attributes.getLength() - 1) {
            attributesString += ",";
        }
    }
    attributesString += "]";
    return attributesString;
}

【讨论】:

  • 感谢克雷格,它对我来说工作得很好,但是如果有多个父节点,例如这个例子,这将不起作用 final String xmlString = "" + "" + "" + "" + " " + "" + "" + "" + "" + "" + "" + "" + "";
猜你喜欢
  • 1970-01-01
  • 2020-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多