java - 如何使用 Java 在 xml 中打印所选父标签内的子标签属性

标签 java xml

我对 XML 文件标签打印和读取有一个疑问。 举个例子:我想从 XML 文件中选择一个特定的标签。在此,我需要读取并打印所选的父标签属性,并打印所有子标签(rubric、div、Interaction、simpleChoice、prompt)属性。我可以获得父标签 ID,但无法获取所有子标签 ID。

public class ReadXmlId {

public static void main(String[] args) throws IOException {
    String filePath = "/Users/myXml/Sample.xml";
    File xmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();
        printElement(doc);
        System.out.println("XML file updated successfully");
    } catch (SAXException | ParserConfigurationException e1) {
        e1.printStackTrace();
    }
}
private static void printElement(Document someNode) {
    NodeList nodeList = someNode.getElementsByTagName("itemBody");
    Node nNode = nodeList.item(0);
    ArrayList<String> listOfArray = new ArrayList<String>();
    for(int z=0,size= nodeList.getLength();z<size; z++) {
        //Value is variable use to print Parent Tag (itemBody) ID
            String Value = nodeList.item(z).getAttributes().getNamedItem("id").getNodeValue();
            listOfArray.add(Value);
            //Syntax to read the child tag
            NodeList nList = nNode.getChildNodes();
            for (int i = 0; i < nList.getLength();i++) {
                Node child = nList.item(i);
                if (child.getNodeType() == Document.ELEMENT_NODE) {
                    if (child.getNodeName().equals("*")) {
                        //Value1 is variable use to print all child Tag (div,p,SimpleChoice and all) ID
                        String Value1 = nList.item(i).getAttributes().getNamedItem("id").getNodeValue();
                        listOfArray.add(Value1);
                        continue;

                    } else {
                         System.out.println("Empty List");  
                    }
                }

            }

      }
     System.out.println("Array List"+listOfArray);
}

}

示例:(id)

<itemBody class="etsmcm01fmt" id="244_item_content_3">
    <rubric class="item_response_information " id="244_item_response_information_21" use="instruction" view="author proctor scorer testConstructor tutor"/>
    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="../Passage/205.qti.xml"/>
    <div class="stimulus_reference " id="244_stimulus_reference_4">
        <p class="introduction passage-intro " id="244_introduction_5">Read<span class="formatted_text text_decoration:underline " id="200244_formatted_text_6">two</span> sentences</p>
    </div>
    <Interaction class="choice_list " id="244_choice_list_12" maxChoices="4" minChoices="0" responseIdentifier="RESPONSE" shuffle="false">
        <prompt id="244_item_stem_8">
            <p class="stem_paragraph " id="244_stem_paragraph_9">story</p>
        </prompt>
        <simpleChoice class="block_choice " id="200244_block_choice_13" identifier="i1">
            <p class="choice_paragraph " id="200244_choice_paragraph_14">North and south</p>
        </simpleChoice>
        <simpleChoice class="block_choice " id="200244_block_choice_15" identifier="i2">
            <p class="choice_paragraph " id="200244_choice_paragraph_16">Sun and Moon</p>
        </simpleChoice>
        <simpleChoice class="block_choice " id="200244_block_choice_17" identifier="i3">
            <p class="choice_paragraph " id="200244_choice_paragraph_18">uncomfortable.</p>
        </simpleChoice>
        <simpleChoice class="block_choice " id="200244_block_choice_19" identifier="i4">
            <p class="choice_paragraph " id="200244_choice_paragraph_20">head.</p>
        </simpleChoice>
    </Interaction></itemBody>

最佳答案

如果我理解正确的话,您正在寻找一种方法来打印<itemBody>内所有元素的所有属性。元素。

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class App {

    public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
        File xmlFile = new File("C:\\test\\testDocXml.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;

        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();

        walkNode(doc);
    }

    private static void walkNode(Node node) {
        NodeList nodeList = node.getChildNodes();

        for (int i = 0; i < nodeList.getLength(); i++) {
            checkChildNode(nodeList.item(i));
        }
    }

    private static void checkChildNode(Node node) {
        if (node.hasChildNodes()) {
            checkAttributes(node);

            walkNode(node);
        }
    }
    private static void checkAttributes(Node node) {
        if (node.hasAttributes()) {
            NamedNodeMap attributes = node.getAttributes();

            printAttributes(attributes);
        }
    }

    private static void printAttributes(NamedNodeMap attributes) {
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);

            if (attribute.getNodeName() == "id") {
                System.out.println("Attribute found: " + attribute.getNodeName() + " : " + attribute.getNodeValue());
            }
        }
    }
}

你会得到如下输出:

Attribute found: id : 244_item_content_3
Attribute found: id : 244_stimulus_reference_4
Attribute found: id : 244_introduction_5
Attribute found: id : 200244_formatted_text_6
Attribute found: id : 244_choice_list_12
Attribute found: id : 244_item_stem_8
Attribute found: id : 244_stem_paragraph_9
Attribute found: id : 200244_block_choice_13
Attribute found: id : 200244_choice_paragraph_14
Attribute found: id : 200244_block_choice_15
Attribute found: id : 200244_choice_paragraph_16
Attribute found: id : 200244_block_choice_17
Attribute found: id : 200244_choice_paragraph_18
Attribute found: id : 200244_block_choice_19
Attribute found: id : 200244_choice_paragraph_20

关于java - 如何使用 Java 在 xml 中打印所选父标签内的子标签属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35318560/

相关文章:

java - 如何在 java 中查找 xml 中缺少的属性

c# - 包含 namespace 的 XDocument

javascript - eBay 查找 API findItemsByKeywords 返回 'Input URL gave a value for header X-EBAY-SOA-OPERATION-NAME but has a conflicting mapped value' 错误

java - Java排列程序详解

java - 如何在java中动态检索常量?

java - 存储迭代器引用

json - 用于在服务器上存储文章的 XML、JSON、YAML 或 CSV?

java - org.apache.xml.security.c14n.CanonicalizationException : Element listFunctions has a relative namespace: xmlns ="xxx_xxx_listFunctions"

JAVA - 如何加速顺序任务

java - 从 Java 应用程序打开命令行