获取xml中处理指令标记内的数据

时间:2014-02-27 08:08:23

标签: java xml dom

这是我的代码:

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

我有几个标签&lt; ?PG 1?&gt; ,&lt; ?PG 2?&gt;,&lt; ?PG 3?>表示页码如何从页面标记中获取数据。

3 个答案:

答案 0 :(得分:2)

  1. 您可以使用递归覆盖xml,而不会遇到凌乱的嵌套for循环。
  2. 您可以将节点类型与PROCESSING_INSTRUCTION_NODE进行比较并提取其内容。
  3. 示例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
    

答案 1 :(得分: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());
        }

希望这有帮助。

答案 2 :(得分:0)

处理指令在DOM( D 项目 O 项目 M odel)中显示为Node.PROCESSING_INSTRUCTION_NODE