I have seen many similar questions on stackoverflow and tried a lot but still no success. So posting my problem.
Here is my program:
- Get the http output of a response which is in xml.
- Store the response in a string.
- Parse the string using xml dom parser.
- Fetch the element.
<RESULTS>
<DEVICE name="qwewewew">
<PORT name="ilo">
<DB_SOURCE>abncd</DB_SOURCE>
<WIRE_TYPE>ilo</WIRE_TYPE>
<CONNECTS>abncd</CONNECTS>
</PORT>
<PORT name="onboard-1">
<DB_SOURCE>abncd</DB_SOURCE>
<WIRE_TYPE>net</WIRE_TYPE>
<CONNECTS>abncd</CONNECTS>
</PORT>
<PORT name="abncd">
<DB_SOURCE>abncd</DB_SOURCE>
<WIRE_TYPE/>
<CONNECTS/>
</PORT>
<PORT name="abncd">
<DB_SOURCE>abncd</DB_SOURCE>
<WIRE_TYPE>fiber</WIRE_TYPE>
<CONNECTS>abncd</CONNECTS>
</PORT>
<PORT name="power">
<DB_SOURCE>abncd</DB_SOURCE>
<WIRE_TYPE/>
<CONNECTS/>
</PORT>
<PORT name="serial">
<DB_SOURCE>abncd</DB_SOURCE>
<WIRE_TYPE>serial</WIRE_TYPE>
<CONNECTS>abncd</CONNECTS>
</PORT>
</DEVICE>
</RESULTS>
Snippet of My program is as follows:
String baseUrl = "http://abcd.eng.xyz.com/wiremap/index.php?action=search&page=0&port_name=&dev_type=like&output=xml&dev_name=w2-fiqa-058";
String xmlRecords = get(baseUrl).asString();
DocumentBuilderFactory factory2 = DocumentBuilderFactory.newInstance();
factory2.setNamespaceAware(true);
DocumentBuilder builder2 = factory2.newDocumentBuilder();
Document document = builder2.parse(new ByteArrayInputStream(xmlRecords.getBytes()));
String test = document.getTextContent();
System.out.println("Value " +test);
System.out.println(document);
Here document is returning null. I am not sure what I am missing.
The
org.w3c.dom.Node#getTextContent
method promises to returnnull
when invoked on:DOCUMENT_NODE
DOCUMENT_TYPE_NODE
NOTATION_NODE
See docs here.
If you want to verify your
Document
contains what's expected, or generally iterate over its nodes, you can iterate overgetChildNodes
.Here's a little recursive method that'll print some debugging info for that XML string, in a self-contained example.
Output