简体   繁体   English

使用Java从XML中提取必需和可选的属性值

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

I have a task in connection with XML parsing (org.w3c.dom) 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>

I would like to collect the super-class and sub-class values in two different ArrayList (the sub-class is optional, so if there is a value than we should add it to the ArrayList , if not, a null should be added to the ArrayList ), in this example the output should be: 我想在两个不同的ArrayList收集super-classsub-class值( sub-class是可选的,因此,如果存在比我们应将其添加到ArrayList ,则不应该将null添加到ArrayList ),在此示例中,输出应为:

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

You could first get descendant elements primary-class thanks to Element#getElementsByTagName(java.lang.String name) then for each of them get the first sub-element whose name is super-class and get the first sub-element whose name is sub-class if it exists otherwise use null . 由于Element#getElementsByTagName(java.lang.String name)您可以首先使后代元素成为primary-class ,然后为每个子元素获取名称为super-class的第一个子元素,并获取名称为sub-class的第一个子元素sub-class如果存在),否则使用null

Something like this: 像这样:

// 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