0

I have an xml and I want to extract some part of that. But I am unable to get it. If I used variables and put every key in variables I can get that part but it is a very lengthy process. So is there any short process for it?

Below is the XML :

<?xml version=\"1.0\" encoding=\"UTF-8\"?><xs:nml xmlns:xs=\"http://www.netgear.com/protocol/transaction/NMLSchema-0.9\" src=\"nas\" dst=\"dpv_1461117132000\" locale=\"en-us\"> <xs:transaction ref-id=\"\" type=\"0\"> <xs:response ref-id=\"njl_id_1941\" status=\"success\"> <xs:result> <xs:get-s resource-id=\"network_link_list\" resource-type=\"network_link_collection\"> <network_link_collection> <network_link resource-id=\"eth0\"> <link>eth0</link> <ifname>eth0</ifname> <speed>1000</speed> <path/> <duplex>full</duplex> <vlanid>0</vlanid> <iptype>ipv4dhcp</iptype> <ipv6type>ipv6dhcp</ipv6type> <ip>0.0.0.0</ip> <subnet>255.255.255.0</subnet> <broadcast>0.0.0.0</broadcast> <ipv6>::</ipv6> <subnet6>::</subnet6> <prefixlength>64</prefixlength> <ipv6_link>::</ipv6_link> <prefixlength_link>64</prefixlength_link> <mac>6C:B0:CE:1C:CA:AE</mac> <mtu>1500</mtu> <router>0.0.0.0</router> <router6>0.0.0.0</router6> <state>down</state> <dnscollection/> <routecollection/> <ntpcollection/> </network_link> </network_link_collection> </xs:get-s> </xs:result> </xs:response> </xs:transaction> 

I want the xml which comes inside network link collection.

2
  • Use a DOM/SAX parser or a third-party library like Beautiful Soup. Commented Feb 8, 2017 at 14:02
  • I am not getting any method to do same.I have a way to find the values of nodes/keys.But not able to get whole xml under network_link_collection Commented Feb 8, 2017 at 14:14

2 Answers 2

4

You can create a map of property key-value pairs fairly easily. You just need to find the nodes that you want to pull out.

NodeList nodeList = doc.getElementsByTagName("network_link").item(0).getChildNodes(); 

ParseResponseXML.java

import java.io.*; import java.net.*; import java.util.*; import javax.xml.parsers.*; import org.w3c.dom.*; public class ParseResponseXML { public static void main(String[] args) { try { File fXmlFile = getResourceAsFile("resources/Response.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); // http://stackoverflow.com/questions/13786607 NodeList nodeList = doc.getElementsByTagName("network_link").item(0).getChildNodes(); Map<String, String> propertyMap = nodeListToMap(nodeList); for (Map.Entry<String, String> entry : propertyMap.entrySet()) { System.out.printf("%-18s => %s%n", entry.getKey(), entry.getValue()); } } catch (Exception e) { e.printStackTrace(); } } private static Map<String, String> nodeListToMap(NodeList nodeList) { Map<String, String> result = new LinkedHashMap<String, String>(); for (int temp = 0; temp < nodeList.getLength(); temp++) { Node node = nodeList.item(temp); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; result.put(element.getTagName(), element.getTextContent()); } } return result; } private static File getResourceAsFile(String resource) throws IOException { ClassLoader loader = Parse.class.getClassLoader(); File resourceFile = null; if (loader instanceof URLClassLoader) { URLClassLoader urlClassLoader = URLClassLoader.class.cast(loader); URL resourceUrl = urlClassLoader.findResource(resource); if ("file".equals(resourceUrl.getProtocol())) { try { URI uri = resourceUrl.toURI(); resourceFile = new File(uri); } catch (URISyntaxException e) { IOException ioException = new IOException("Unable to get file through class loader: " + loader); ioException.initCause(e); throw ioException; } } } if (resourceFile == null) { throw new IOException("Unable to get file through class loader: " + loader); } return resourceFile; } } 

Response.xml

Make sure you have the </xs:nml> closing tag at the end of the XML.

<?xml version="1.0" encoding="UTF-8"?> <xs:nml xmlns:xs="http://www.netgear.com/protocol/transaction/NMLSchema-0.9" src="nas" dst="dpv_1461117132000" locale="en-us"> <xs:transaction ref-id="" type="0"> <xs:response ref-id="njl_id_1941" status="success"> <xs:result> <xs:get-s resource-id="network_link_list" resource-type="network_link_collection"> <network_link_collection> <network_link resource-id="eth0"> <link>eth0</link> <ifname>eth0</ifname> <speed>1000</speed> <path /> <duplex>full</duplex> <vlanid>0</vlanid> <iptype>ipv4dhcp</iptype> <ipv6type>ipv6dhcp</ipv6type> <ip>0.0.0.0</ip> <subnet>255.255.255.0</subnet> <broadcast>0.0.0.0</broadcast> <ipv6>::</ipv6> <subnet6>::</subnet6> <prefixlength>64</prefixlength> <ipv6_link>::</ipv6_link> <prefixlength_link>64</prefixlength_link> <mac>6C:B0:CE:1C:CA:AE</mac> <mtu>1500</mtu> <router>0.0.0.0</router> <router6>0.0.0.0</router6> <state>down</state> <dnscollection /> <routecollection /> <ntpcollection /> </network_link> </network_link_collection> </xs:get-s> </xs:result> </xs:response> </xs:transaction> </xs:nml> 

Output

link => eth0 ifname => eth0 speed => 1000 path => duplex => full vlanid => 0 iptype => ipv4dhcp ipv6type => ipv6dhcp ip => 0.0.0.0 subnet => 255.255.255.0 broadcast => 0.0.0.0 ipv6 => :: subnet6 => :: prefixlength => 64 ipv6_link => :: prefixlength_link => 64 mac => 6C:B0:CE:1C:CA:AE mtu => 1500 router => 0.0.0.0 router6 => 0.0.0.0 state => down dnscollection => routecollection => ntpcollection => 

Unwrap XML

If you want to unwrap a node, you can perform the following.

import java.io.*; import java.net.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; import org.xml.sax.SAXException; public class ParseResponseXML { public static void main(String[] args) { try { Document inputDoc = load("resources/Response.xml"); Document outputDoc = unwrap(inputDoc, "network_link_collection"); write(outputDoc, "NetworkLinkCollection.xml"); } catch (Exception e) { e.printStackTrace(); } } public static Document load(String resource) throws IOException, ParserConfigurationException, SAXException { File file = getResourceAsFile(resource); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); return dBuilder.parse(file); } public static void write(Document doc, String filename) throws TransformerException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filename)); // StreamResult result = new StreamResult(System.out); // Output to console. transformer.transform(source, result); } public static Document unwrap(Document doc, String tagName) throws ParserConfigurationException { Node node = doc.getElementsByTagName(tagName).item(0); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document result = dBuilder.newDocument(); Node importNode = result.importNode(node, true); result.appendChild(importNode); return result; } private static File getResourceAsFile(String resourceName) throws IOException { ClassLoader loader = ParseResponseXML.class.getClassLoader(); File resourceFile = null; if (loader instanceof URLClassLoader) { URLClassLoader urlClassLoader = URLClassLoader.class.cast(loader); URL resourceUrl = urlClassLoader.findResource(resourceName); if ("file".equals(resourceUrl.getProtocol())) { try { URI uri = resourceUrl.toURI(); resourceFile = new File(uri); } catch (URISyntaxException e) { IOException ioException = new IOException("Unable to get file through class loader: " + loader); ioException.initCause(e); throw ioException; } } } if (resourceFile == null) { throw new IOException("Unable to get file through class loader: " + loader); } return resourceFile; } } 

NetworkLinkCollection.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?> <network_link_collection> <network_link resource-id="eth0"> <link>eth0</link> <ifname>eth0</ifname> <speed>1000</speed> <path /> <duplex>full</duplex> <vlanid>0</vlanid> <iptype>ipv4dhcp</iptype> <ipv6type>ipv6dhcp</ipv6type> <ip>0.0.0.0</ip> <subnet>255.255.255.0</subnet> <broadcast>0.0.0.0</broadcast> <ipv6>::</ipv6> <subnet6>::</subnet6> <prefixlength>64</prefixlength> <ipv6_link>::</ipv6_link> <prefixlength_link>64</prefixlength_link> <mac>6C:B0:CE:1C:CA:AE</mac> <mtu>1500</mtu> <router>0.0.0.0</router> <router6>0.0.0.0</router6> <state>down</state> <dnscollection /> <routecollection /> <ntpcollection /> </network_link> </network_link_collection> 
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to make this work with xml namespaces? This method cuts the namespace declarations out too.
0

Great response from Mr. Polywhirl!! Thanks a lot!! I only want to add that if what you want is to extract a part of the xml but without including xml header (), like me, you have to add this in the "write" method:

transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.