How to read child XML using XPath in Java - java

The XML file is as :
Xml File
Code I have written:
List queryXmlUsingXpathAndReturnList(String xml, String xpathExpression) {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance()
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder()
Document doc = dBuilder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)))
doc.getDocumentElement().normalize()
XPath xPath = XPathFactory.newInstance().newXPath()
NodeList nodeList = (NodeList) xPath.compile(xpathExpression).evaluate(doc, XPathConstants.NODESET)
List returnElements = new ArrayList<>()
nodeList.each { n ->
returnElements.add(n.getTextContent())
}
When I am passing the xpath as:
/Envelope/Body/CommandResponseData/OperationResult/Operation/ParameterList/ListParameter/StringElement
It returns all the values.
But I want to return only the ListParameter values whose name="PackageTypeList".
For that I am using the xpath as:
/Envelope/Body/CommandResponseData/OperationResult/Operation/ParameterList/ListParameter[#name='PackageTypeList']/StringElement
But it returns list as null.

I guess you miss "CommandResult" between "CommandResponseData" and "OperationResult" in your XPath-Expression.

Related

How to fetch a value from XML using XPATH

This is my xml and i wanted to fetch value of Id tag '4654'
<Entity>
<acc>
<id>4654</id>
<name>abc</name>
</acc>
<acc>
<id>5465</id>
<name>xyz</name>
</acc>
I am using this code to retrieve the Id value
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList node = (NodeList) xPath.evaluate("/Entity/acc/id/text()", document, XPathConstants.NODE);
System.out.println("node length:"+node.getLength());
System.out.println("node value:"+ node.item(0).getNodeValue());
return node.item(0).getNodeValue();
Output returns null
Any help would be appreciated
You need to use XPathConstants.NODESET instead of XPathConstants.NODE
or you can keep it as XPathConstants.NODE and change the evaluate to return Node
Node node = (Node) xPath.evaluate("/Entity/acc/id/text()", document, XPathConstants.NODE);

How read more XSD schemas with Xpath?

I have 2 XSD schemas first.xsd and second.xsd
In first.xsd is:
<xs:include schemaLocation="second.xsd" />
and I want read elements in second.xsd.
I have defined:
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(new FileInputStream("first.xsd"));
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList result1 = null;
result1 = (NodeList) xPath.compile("//element[#name='List']").evaluate(xmlDocument, XPathConstants.NODESET);
for (int k = 0; k < result1.getLength(); k++) {
Element ele = (Element)result1.item(k);
System.out.println(ele.getAttribute("type")); }
Problem is program didnt find element list in second.xsd.
Can I define some as this?
Document xmlDocument = builder.parse(new FileInputStream("first.xsd","second.xsd"));
Is something as LSResourceResolver but that is for validation.
Can I use it for my code?
Thank you for advices.

Node.getNodeValue() returns null in java

I am trying to find the node value by evaluating the xpath expression.
String resp="<response><result><phone>1234</phone><sys_id>dfcgf34dfg56</sys_id></result></response>";
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFactory.newDocumentBuilder();
org.w3c.dom.Document dDoc = builder.parse(new InputSource(new ByteArrayInputStream(resp.getBytes("utf-8"))));
XPath xPath = XPathFactory.newInstance().newXPath();
Node node = (Node) xPath.evaluate("//response/result/sys_id", dDoc, XPathConstants.NODE);
System.out.println(node.getNodeName()+" , "+node.getNodeValue());
This gives the output : sys_id , null when the sys_id is clearly not null.
The xpath evaluator returns correct value.
Can anybody point out any error?
Thank you!
I am not an expert in XPath, but based on this Stack Overflow article I was able to produce the following code which does work correctly:
String resp = "<response><result><phone>1234</phone><sys_id>dfcgf34dfg56</sys_id></result></response>";
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFactory.newDocumentBuilder();
org.w3c.dom.Document dDoc = builder.parse(new InputSource(new ByteArrayInputStream(resp.getBytes("utf-8"))));
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("//response/result/sys_id"); // these 2 lines
String str = (String) expr.evaluate(dDoc, XPathConstants.STRING); // are different
System.out.println(str);
Output:
dfcgf34dfg56
There is a typo in your code: When parsing the input you use a variable called "resp" but you defined a vaiable called "resp1".
Dispite the typo: In order to catch the TextContent use node.getTextContent()
System.out.println(node +": " + node.getNodeName() + ", " + node.getTextContent());
The reason why your code returned null is: You are extracting an ELEMENT node and the result of getNodeValue() depends on the node type (see table in API) and will always return null for ELEMENT nodes.

java dom search xml

hello i have this xml
<?xml version="1.0" encoding="utf-8" standalone="no"?><?xml-stylesheet type="text/xsl" href="new2.xsl"?>
<patients>
<patient>
<stoixeia_astheni>
<arithmos_eksetasis>1</arithmos_eksetasis>
<imerominia_eksetasis>11/12/2005</imerominia_eksetasis>
<amka>14385</amka>
</stoixeia_astheni>
<stoixeia_epikoinonias>
<dieuthinsi>Μητσοπούλου 20</dieuthinsi>
</stoixeia_epikoinonias>
<loipa_stoixeia>
<fylo>Aρρεν</fylo>
</loipa_stoixeia>
</patient>
<patient>
same code here
</patient>
</patients>
and i want to search this by amka value.
i have tried this:
Document doc = docBuilder.parse(filepath);
NodeList root= doc.getDocumentElement().getChildNodes();
for(int i=0; i<root.getLength(); i++){
if(root.item(i).getChildNodes().item(0).getChildNodes().item(2).getNodeValue()=="14385"){
pw.println("Gataki<br>");
}
}
but runtime error occurs
Any help would be useful.
Use this xpath
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/patients/patient/stoixeia_astheni/amka/text()");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
Just in case takke a look at this xpath syntaxis
/ Selects from the root node
// Selects nodes in the document from the current node that match the selection no matter where they are
. Selects the current node
.. Selects the parent of the current node
# Selects attributes

Building DOM document from xml string gives me a null document

I'm trying to use the DOM library to parse a string in xml format. For some reason my document contains nulls and I run into issues trying to parse it. The string variable 'response' is not null and I am able to see the string when in debug mode.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(response));
Document doc = builder.parse(is);
NodeList nodes = doc.getElementsByTagName("BatchFile");;
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList batchItem = element.getChildNodes();
String uri = batchItem.item(0).getNodeValue();
String id = batchItem.item(1).getNodeValue();
String fqName = batchItem.item(2).getNodeValue();
}
Highlighting over the line Document doc = builder.parse(is); after it has run shows the result of [#document: null].
Edit: I've managed to not got an empty doc now but the string values are still null (at end of code). How would I get the value of something like this
<GetBatchFilesResult>
<BatchFile>
<Uri>uri</Uri>
<ID>id</ID>
<FQName>file.zip</FQName>
</BatchFile>
</GetBatchFilesResult>
You can also use getTextContent(). getNodeValue will return null for elements. Besides, you'd better use getElementsByTagName, since white spaces are also treated as one of the child nodes.
Element element = (Element) nodes.item(i);
String uri = element.getElementsByTagName("Uri").item(0).getTextContent();
String id = element.getElementsByTagName("ID").item(0).getTextContent();
String fqName = element.getElementsByTagName("FQName").item(0).getTextContent();
Check Node API document to see what type of nodes will return null for getNodeValue.
I found the solution. Seems stupid that you have to do it this way to get a value from a node.
Element element = (Element) nodes.item(i);
NodeList batchItem = element.getChildNodes();
Element uri = (Element) batchItem.item(0);
Element id = (Element) batchItem.item(1);
Element fqName = (Element) batchItem.item(2);
NodeList test = uri.getChildNodes();
NodeList test1 = id.getChildNodes();
NodeList test2 = fqName.getChildNodes();
String strURI= test.item(0).getNodeValue();
String strID= test1.item(0).getNodeValue();
String strFQName= test2.item(0).getNodeValue();

Categories

Resources