簡體   English   中英

使用Java從XML中提取必需和可選的屬性值

[英]Extracting required and optional attribute values from XML with Java

我有一個與使用Java進行XML解析(org.w3c.dom)有關的任務。

<?xml version="1.0" encoding="utf-8"?>
<documents>
    <document id="001">
        <metadata>
            <primary-class>
                <super-class super-class="some-value"/>
                <sub-class sub-class="other-value"/>
            </primary-class>
        </metadata>
    </document>
    <document id="002">
        <metadata>
            <primary-class>
                <super-class super-class="some-value"/>
            </primary-class>
        </metadata>
    </document>
</documents>

我想在兩個不同的ArrayList收集super-classsub-class值( sub-class是可選的,因此,如果存在比我們應將其添加到ArrayList ,則不應該將null添加到ArrayList ),在此示例中,輸出應為:

[some-value][some-value]
[other-value][null]

由於Element#getElementsByTagName(java.lang.String name)您可以首先使后代元素成為primary-class ,然后為每個子元素獲取名稱為super-class的第一個子元素,並獲取名稱為sub-class的第一個子元素sub-class如果存在),否則使用null

像這樣:

// Parse my XML doc using a DOM parser
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(source);

// Get all descendant elements `primary-class`
NodeList nl = doc.getElementsByTagName("primary-class");

// Initialize my lists 
int length = nl.getLength();
List<String> superClasses = new ArrayList<>(length);
List<String> subClasses = new ArrayList<>(length);

// For each element `primary-class` found
for (int i = 0; i < nl.getLength(); i++){
    Element element = (Element) nl.item(i);

    // Add the super class to the list
    NodeList nlSuperClasses = element.getElementsByTagName("super-class");
    superClasses.add(((Element) nlSuperClasses.item(0)).getAttribute("super-class"));

    // Add the sub class to the list if it exists, null otherwise
    NodeList nlSubClasses = element.getElementsByTagName("sub-class");
    subClasses.add(
        nlSubClasses.getLength() > 0 ? 
       ((Element) nlSubClasses.item(0)).getAttribute("sub-class") : 
       null
    );
}

暫無
暫無

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

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