簡體   English   中英

Java 獲取 XML 節點

[英]Java get XML nodes

我想獲得前兩個服務作者的姓名。

我有以下 XML 示例:

<ServiceSchema:id>10</ServiceSchema:id>
<ServiceSchema:name>Service 10</ServiceSchema:name>
<ServiceSchema:authorInfos>
    <ServiceSchema:authorInfo>
        <ServiceSchema:id>1</ServiceSchema:id>
        <ServiceSchema:name>Service Author 1</ServiceSchema:name>
    <ServiceSchema:authorInfo>
    <ServiceSchema:authorInfo>
        <ServiceSchema:id>2</ServiceSchema:id>
        <ServiceSchema:name>Service Author 2</ServiceSchema:name>
    <ServiceSchema:authorInfo>
</ServiceSchema:authorInfos>

<ServiceSchema:requirements>
    <ServiceSchema:requirement>
        <ServiceSchema:id>1</ServiceSchema:id>
        <ServiceSchema:name>Requirement 1</ServiceSchema:name>
        <ServiceSchema:authorInfos>
            <ServiceSchema:authorInfo>
                <ServiceSchema:id>5</ServiceSchema:id>
                <ServiceSchema:name> Requirement Author 5</ServiceSchema:name>
            <ServiceSchema:authorInfo>
        </ServiceSchema:authorInfos>
    </ServiceSchema:requirement>
.....

我可以使用以下代碼獲取所有名稱節點:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource inputSource = new InputSource(new ByteArrayInputStream (xml.getBytes("utf-8")));
Document xmldocument = db.parse(inputSource);
NodeList nodeList = xmldocument.getElementsByTagNameNS("*", "name");

但我不知道如何只獲得外部作者的名字。

謝謝你。

更新:

我完全想做的是:我為不同的節點搜索不同的 xml 文件。 上面的 xml 文件只是一個例子。

例如:

searchElementsXml = new String[]{"name", "id", "version", "description", "keywords", "authorInfos.authorInfo.name", "status"};

我有一些字段可以出現很多值。 喜歡作者信息。

所以我需要類似的東西:

NodeList nodes = doc.getElementsByTagName("ServiceSchema:authorInfos:authorinfo:name");

有沒有好的解決方案?

如果我正確理解了您想要什么,我建議您獲取所有作者信息 (ServiceSchema:authorInfo),然后獲取每個 authorInfo 的名稱節點。

你的 XML 是否正確我看不到 ServiceSchema:authorInfo 標簽正在關閉
你能更新你正在尋找的輸出嗎? 要獲取作者信息,您可以使用以下代碼 NodeList nodes = doc.getElementsByTagName("ServiceSchema:authorInfos");

她是詳細的執行代碼

File fXmlFile = new File("/Users/Downloads/test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("ServiceSchema:authorInfos");
for (int temp = 0; temp < nodes.getLength(); temp++) {
    Node nNode = nodes.item(temp);
    System.out.println(" Current Author Element :" + nNode.getNodeName());
    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
        Element eElement = (Element) nNode;
        System.out.println("Author Info Name : " + eElement.getElementsByTagName("ServiceSchema:authorInfo").getLength());
    }
}

我最終按照其他人的建議使用了 xpath。 效果很好-

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM