Reputation: 57
I have a large XML file that I want to parse
XML - The XML file has over 300 cases and other tags i'm only interested in the Cases. What I want todo is take all the cases and everything in the case tag and save it in a new DOM doc that only holds the cases, Once I have this New DOM I want to send it to another class that will take the information and format it into a word document( but i'll takle that once I get there)
an example of my XML is
<suite>
<cases>
<case>
<id/>
<title/>
<type/>
<priority/>
<estimate/>
<references/>
<custom>
<functional_area/>
<technology_dependence/>
<reviewed/>
<steps_completed>
</steps_completed>
<preconds> </preconds>
<steps_seperated>
<step>
<index/>
<content>
</content>
<expected>
</expected>
</step>
<step>
<index/>
<content>
</content>
<expected>
</expected>
</step>
<step>
</steps_seperated>
</custom>
</case>
</suite>
</cases>
There are about 400 of these case nodes
My java
setting up the initial
private void setXMLdoc(String path){
xmlDoc = getDocument(path) ;
}
getting the xml file
private Document getDocument(String path) {
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(path);
} catch (ParserConfigurationException ex) {
Logger.getLogger(ImportXML.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(ImportXML.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ImportXML.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
would this create a new doc that only contains the cases?
NodeList fList = xmlDoc.getElementsByTagName("case");
also how would I print out all elements todo with the case? / print out all the elements todo with all the cases
Thanks in advance - im still pretty new so sorry if this question doesn't make sense or seems a bit basic
Upvotes: 0
Views: 132
Reputation: 3762
The approximate code will be
DOMParser parser=new DOMParser();
InputSource source=new InputSource(<the XML file/network stream>);
parser.parse(source);
Element docElement=parser.getDocument().getDocumentElement();
XPath xPath=xPathFactory.newXPath();
XPathExpression expression_=xPath.compile("//case");
NodeList list_=(NodeList)expression_.evaluate(docElement,XPathConstants.NODESET);DocumentBuilder documentBuilder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document newDocument=documentBuilder.newDocument();
Element newElement=newDocument.createElement("SOME_NAME");
newDocument.appendChild(newElement);
for(int i=0;i<list_.getLength();i++){Node n=newDocument.importNode(list_.item(i),true);newElement.appendChild(n);}
then send the 'newDocument' to the other class
Upvotes: 1