java - 使用java : list. item(i).getFirstChild()遍历xml DOM

标签 java xml

我正在尝试遍历 XML 标签,并且使用 list.item(i).getFirstChild(); 但它返回:[# text: ]。 据我所知,此方法应该返回“标记名称”或 null,但这里它返回备用标记名称和 [# text: ]

[# 文本:]

标签名

[# 文本:]

标签名 我正在使用的代码是:

public  void readXML() throws ParserConfigurationException, SAXException, IOException, TransformerException
    {
        String rootNode=null;
        //Get Document Builder
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Transformer tx = TransformerFactory.newInstance().newTransformer();
        tx.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("C:/Users/ve00p5199/Desktop/xml/test.xml"));
        NodeList list = doc.getElementsByTagName("*");

        for (int i = 0; i < list.getLength(); i++) {
            //System.out.println(list.item(i).getNodeName());
            if(list.item(i).getNodeName().equalsIgnoreCase("shape")||list.item(i).getNodeName().equalsIgnoreCase("Textbox")||list.item(i).getNodeName().equalsIgnoreCase("Button")){
//              System.out.println(list.item(i).getNodeName());
                Node node = findPropertyTagAndValue(list.item(i).getFirstChild(), "PropertyValue", "conditionContainer");
                if (node != null) {
                    System.out.println("Node Name = " + node.getNodeName() + "; Value = " + node.getTextContent());
                    DOMSource src = new DOMSource(list.item(i));
                    StringWriter sr = new StringWriter();
                    Result res = new StreamResult(sr);
                    tx.transform(src, res);
                    System.out.println(sr);
                }
            }
        }
    }

    public static Node findPropertyTagAndValue(Node node, String propertyTag, String propertyValue) {
        if (node == null) {
            // The node we're looking for does not exist
            return null;
        } else if (node.getNodeType() != Node.ELEMENT_NODE) {
            // Move to the next sibling node
            return findPropertyTagAndValue(node.getNextSibling(), propertyTag, propertyValue);
        } else if (node.getNodeName().equalsIgnoreCase(propertyTag) && node.getTextContent().equalsIgnoreCase(propertyValue)) {
            // We found the node we are looking for
            return node;
        } else if (node.hasChildNodes()) {
            // Check into the child nodes
            Node childNode = findPropertyTagAndValue(node.getFirstChild(), propertyTag, propertyValue);
            if (childNode == null) {
                // Nothing found in child node, so move to next sibling
                childNode = findPropertyTagAndValue(node.getNextSibling(), propertyTag, propertyValue);
            }
            return childNode;
        } else {
            // Move to the next sibling
            return findPropertyTagAndValue(node.getNextSibling(), propertyTag, propertyValue);
        }
    }

我的 XML 是:

<Diagram>
                <Widgets>

                    <Shape>
                        <ShapeType>H2</ShapeType>
                        <Annotation>
                            <Properties>
                                <PropertyValue PropertyName="field_label">label.modelSeriesCd</PropertyValue>
                                <PropertyValue PropertyName="ContainerType">conditionContainer</PropertyValue>
                            </Properties>
                        </Annotation>
                        <FootnoteNumber>1</FootnoteNumber>
                        <Name>label.modelSeriesCd</Name>
                        <Rectangle>
                            <Rectangle X="14" Y="94" Width="43" Height="12" />
                        </Rectangle>
                    </Shape>
                    </Diagram>
                </Widgets>

请解释一下...

最佳答案

NodeList list = object.getElementsByTagName("*");
    for (int i = 0; i < list.getLength(); i++) {
        Node listNode = nodeList.item(i);
        if (Node.ELEMENT_NODE == listNode.getNodeType()) {
            String nodeName = listNode.getNodeName();
            if (nodeName.equalsIgnoreCase("shape")
                    || nodeName.equalsIgnoreCase("Textbox")
                    || nodeName.equalsIgnoreCase("Button")) {

                Node node = findPropertyTagAndValue(listNode, "PropertyValue", "conditionContainer");
                if (node != null) {
                    System.out.println("Node Name = " + node.getNodeName() + "; Value = " + node.getTextContent());
                    DOMSource src = new DOMSource(list.item(i));
                    StringWriter sr = new StringWriter();
                    Result res = new StreamResult(sr);
                    tx.transform(src, res);
                    System.out.println(sr);
                }
            }
        }
    }


 /**
 * No Need to check for all those things. Only * will return all elements
 * including #text node. If you give proper node name then it will return
 * those node's only That's why there's node need for checking ELEMENT_NODE
 * in finding propertTags
 */

  public static Node findPropertyTagAndValue(Node node, String propertyTag, String propertyValue) {
    if (Node.ELEMENT_NODE == node.getNodeType()) {
        NodeList nodeList = ((Element) node).getElementsByTagName(propertyTag);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node listNode = nodeList.item(i);
            if (listNode.getTextContent().equalsIgnoreCase(propertyValue)) {
                return listNode;
            }
        }
    }
    return null;
}

关于java - 使用java : list. item(i).getFirstChild()遍历xml DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31152747/

相关文章:

java - 从外部 json 文件导入新顶点

java - 无法使用主机名连接到 Android 服务器

java - 我如何编写带有未知单词的JSGF语法文件?

node.js - 如何使用 Node 中 native 的请求 promise 来使用 XML 主体/内容类型 header 进行 POST?

c# - 如何在 C# 中按以...开头的属性选择节点

Java android google maps集群,点击它们后更改标记中的图标

java - 当我尝试在 Android Studio 0.6.1 上创建新项目时出现 Gradle 同步错误

java - 如何在 Spring Boot 应用程序中将 XML Prolog <?xml version = "1.0"encoding = "UTF-8"?> 插入到 Rest XML 响应

java - 使用 Qualifier 注入(inject) Autowiring 的依赖项失败

java - 设置为 View.VISIBLE 后,Android Button 需要点击几次才能工作