2014-02-27 51 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