如何使用Java在xml中的选定父标记内打印子标记属性

时间:2016-02-10 14:59:14

标签: 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>

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您正在寻找一种方法来打印<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

答案 1 :(得分:0)

在上述XML中的标记(交互)之间打印属性 id 的值。我使用Wesley代码并做了一些简单的更改。

public static void main(String[] args) throws IOException,ParserConfigurationException, SAXException {
    String filePath = "/Users/myXml/SampleXml.xml";
    File xmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(xmlFile);
    doc.getDocumentElement().normalize();
        printElement(doc);
        System.out.println("XML file updated successfully");

}
private static void printElement(Document someNode) {
    NodeList nodeList = someNode.getElementsByTagName("Interaction");

    Node nNode = nodeList.item(0);
    for (int i = 0; i < nodeList.getLength(); i++) {
        checkChildNode(nNode);
    }
}
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());
        }
   }

}

}