2014-02-27 22 views
2

這裏是我的代碼:獲取數據

void validate(String fileLocation){ 
    try{ 
     DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder = factory.newDocumentBuilder(); 
     Document document = builder.parse(new File(fileLocation)); 
     String[] pageContent=new String[100]; 
     for (int i = 0; i < pageContent.length; i++) { 
      String currentPageContent= document.getElementsByTagName("?PG").item(i).getTextContent(); 
      System.out.println("the Current Page content is "+currentPageContent); 
      pageContent[i]=currentPageContent; 
     } 
    }catch(Exception e){ 
     e.printStackTrace(); 
    } 
} 

我有幾個標籤爲< PG 1>,< PG 2>,< PG 3>表示頁??????數字我怎麼能從頁面標籤獲取數據。

+0

這對我來說看起來不像是有效的XML--所以你不能用XML解析器處理它。 –

+0

你知道如何提取處理指令標籤的值嗎? – user3111030

+0

您是否有示例XML片段,說明如何使用它們?您的代碼示例有點無益 - 問題中沒有足夠的信息來回答它。 –

回答

2
  1. 您可以使用遞歸走在你不xml凌亂嵌套for循環。
  2. 您可以比較節點類型爲PROCESSING_INSTRUCTION_NODE並提取其內容。

示例XML:

<?xml version="1.0" encoding="UTF-8" ?> 
<test> 
    <ID>Test1</ID> 
    <TestType name="abc"> 
    <AddressRange start="0x00000000" end="0x0018ffff" /> 
    </TestType > 
    <TestType name="RAM"> 
    <AddressRange start="0x00400000" end="0x00407fff" /> 
    </TestType > 
    <?PITarget PIContent?> 
    <?PISource PISome?> 
</test> 

代碼:

public static void main(String[] args) throws ParserConfigurationException, 
      SAXException, IOException { 
     FileInputStream path = new FileInputStream("text.xml"); 
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder = factory.newDocumentBuilder(); 
     Document document = builder.parse(path); 
     System.out.println(); 
     traverse(document.getDocumentElement()); 

    } 

    public static void traverse(Node node) { 
     NodeList list = node.getChildNodes(); 
     for (int i = 0; i < list.getLength(); i++) { 
      Node currentNode = list.item(i); 
      traverse(currentNode); 

     } 

     if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { 
      System.out.println("This -> " + node.getTextContent()); 
     } 

    } 

給人,

This -> PIContent 
This -> PISome 
0

如果你想在你的代碼讀取Processing Instructions比你應該做這樣的事情:

 NodeList currentPageContent= document.getChildNodes(); 
     for (int i = 0; i < currentPageContent.getLength(); i++) { 
      Node node = currentPageContent.item(i); 
      if(node.getNodeType()==Node.PROCESSING_INSTRUCTION_NODE) 
       System.out.println("the Current Page content is "+ node.getNodeType()+ " : " + node.getNodeName() + " : " + node.getTextContent()); 
     } 

希望這會有所幫助。

0

處理指令被暴露在DOM(d ocument ö bject 中號 Odel等)作爲Node.PROCESSING_INSTRUCTION_NODE