2016-02-10 68 views
0

我對XML文件標記打印和讀取有一個疑問。舉個例子:我想從XML文件中選擇一個特定的標籤。在這我需要閱讀和打印選定的父標記屬性,並打印所有的子標記(rubric,div,Interaction,simpleChoice,提示)屬性。我可以獲取父標記ID,但我沒有獲取所有子標記ID。如何在xml中使用Java在選定父標記內打印子標記屬性

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> 
+0

那麼,什麼是您的實際問題?你有什麼問題?你有任何錯誤? –

+0

我想你可以看到上面的XML文件。我需要打印父標籤**(Item Body)**中每個標籤的** ID ** **。包括父標籤,我從大的Xml文件中選擇這個Item Body標籤a,它有很多標籤。 –

+0

也許[XPath](https://docs.oracle.com/javase/tutorial/jaxp/xslt/xpath.html)可以提供幫助 – ThoFin

回答

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 
+0

您好,Wesley De Keirsmaeker,感謝您爲我的查詢提供的出色解決方案。 **我只需要屬性(ID)**。 –

+0

我試圖通過這種方法獲取屬性(ID)** attribute.getNamedItem(「id」)**。 –

+0

然後在attribute.getNodaName()==「id」上添加一個檢查。 –

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()); 
     } 
    } 

} 

}

相關問題