user3111030 user3111030 - 3 months ago 15
Java Question

get data within a processing instruction tag in xml

here's my code :

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


i have several tags as < ?PG 1 ?> , < ?PG 2 ?>,< ?PG 3 ?> denoting page numbers how can i get get the data from page tag.

Answer
  1. You can use recursion to go over the your xml without messy nested for loops.
  2. You can compare the Node type to be PROCESSING_INSTRUCTION_NODE and extract its contents.

Example 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>

Code:

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

    }

Gives,

This -> PIContent
This -> PISome
Comments