This is my XML.
<Operations>
<Operation Name="OperationName1">Entity details1</Operation>
<Operation Name="OperationName2">Entity details2</Operation>
<Operation Name="OperationName3">Entity details3</Operation>
<Operation Name="OperationName4">Entity details4</Operation>
</Operations>
In this I need to read each child nodes as a string variable. Using DOM I am trying like this.
NodeList items = root.getElementsByTagName("Operation");
for (int i=0;i<items.getLength();i++)
{
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j=0;j<properties.getLength();j++){
Node property = properties.item(j);
}
}
Now as for my understand the items is having all the child nodes now I need to store each child node like this.
String ch_node="<Operation Name="OperationName4">Entity details4</Operation>"
Is there any default method that will give me the child node xml or I need to create again with node name,value and atrributes?
I have tried with SAX parser also but do not know how to get.
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("operation")) {
op_Name=attributes.getValue(0);
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
}
You can try DOM and Transformer
Transformer tx = TransformerFactory.newInstance().newTransformer();
tx.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("1.xml"));
NodeList list = doc.getElementsByTagName("Operation");
for (int i = 0; i < list.getLength(); i++) {
DOMSource src = new DOMSource(list.item(i));
StringWriter sr = new StringWriter();
Result res = new StreamResult(sr);
tx.transform(src, res);
System.out.println(sr);
}
output
<Operation Name="OperationName1">Entity details1</Operation>
<Operation Name="OperationName2">Entity details2</Operation>
<Operation Name="OperationName3">Entity details3</Operation>
<Operation Name="OperationName4">Entity details4</Operation>