How I can extract parameters from xml? - java

How I can extract value Total topics?
<?xml version="1.0"?>
<config>
<command param = "Total topics" > Check title
</command>
</config>
I know that for extracting value of Check title I need such code:
XPathExpression expr = xpath.compile("//command/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
Help me with param, please.

XPathExpression expr = xpath.compile("//command[#param]/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
I've not compiled it but to select an attribute you'll need to used #attributeName after the node is selected.

How about using # for attribute? Try with
XPathExpression expr = xpath.compile("//command/#param");

Related

How to write XPath to get node attribute value from a "Name Space XML" in Java

INPUT_XML:
<?xml version="1.0" encoding="UTF-8">
<root xmlns:ns1="http://path1/schema1" xmlns:ns2="http://path2/schema2">
<ns1:abc>1234</ns1:abc>
<ns2:def>5678</ns2:def>
</root>
In Java, I am trying to write XPath expression which will get the value corresponding to this attribute "xmlns:ns1" from the above INPUT_XML string content.
I've tried the following:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(INPUT_XML);
String xpathExpression = "/root/xmlns:ns1";
// Create XPathFactory object
XPathFactory xpathFactory = XPathFactory.newInstance();
// Create XPath object
XPath xpath = xpathFactory.newXPath();
// Create XPathExpression object
XPathExpression expr = xpath.compile(xpathExpression);
// Evaluate expression result on XML document
NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
But the above code is not giving the expected value of the specified attribute i.e. xmlns:ns1. I heavily suspect the xPathExpression is wrong. Please suggest with the right XPath expression or the right approach to tackle this issue.
If you're using an XPath 1.0 processor, or a XPath 2.0 processor with XPath 1.0 compatibility mode turned on, you can use the namespace axis to select the namespace value.
You will need to make the following change in your code:
String xpathExpression = "/root/namespace::ns1"
The xmlns:ns1="http://path1/schema1" and xmlns:ns2="http://path2/schema2" are not attributes, but namespace declarations. You cannot retrieve them with an XPath declaration so easily (there is XPath function namespace-uri() for this purpose, but root element does not have any namespace, it only defines them for future use).
When using DOM API you could use method lookupNamespaceURI():
System.out.println("ns1 = " + doc.getDocumentElement().lookupNamespaceURI("ns1"));
System.out.println("ns2 = " + doc.getDocumentElement().lookupNamespaceURI("ns2"));
When using XPath you could try following expressions:
namespace-uri(/*[local-name()='root']/*[local-name()='abc'])
namespace-uri(/*[local-name()='root']/*[local-name()='def'])

XPath for text of node?

I'm trying to get to the content of STRING-VALUE where comparator has VALUE = item.auxiliaryData.productRef.brandName
I tried to use the following code,
XPathExpression expr = xpath.compile
("//comparator[contains(VALUE,'item.auxiliaryData.productRef.ancestorCategoryIds')]//STRING-VALUE");
productRefs = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
This is what I'm trying to parse
<comparator NAME="equals">
<VALUE>item.auxiliaryData.productRef.brandName</VALUE>
<CONSTANT>
<DATA-TYPE>java.lang.STRING</DATA-TYPE>
<STRING-VALUE>Ariat</STRING-VALUE>
</CONSTANT>
</comparator>
<comparator NAME="equals">
<VALUE>item.auxiliaryData.productRef.ID</VALUE>
<CONSTANT>
<DATA-TYPE>java.util.Collection</DATA-TYPE>
<STRING-VALUE>84332</STRING-VALUE>
<STRING-VALUE>79904</STRING-VALUE>
<STRING-VALUE>82203</STRING-VALUE>
</CONSTANT>
</comparator>
This XPath,
string(//comparator[VALUE='item.auxiliaryData.productRef.brandName']//STRING-VALUE)
will return "Ariat" directly as requested.
Your xpath needs to be corrected :
//comparator[contains(VALUE,'item.auxiliaryData.productRef.brandName')]//STRING-VALUE
You were using item.auxiliaryData.productRef.ancestorCategoryIds

How to edit attribute using XPath in Android

I want to use XPath to search for a task_status while looking for a uuid.
Here is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<Test1>
<typ>task</typ>
<datestamp>20150602153306</datestamp>
<datecreate>20150602153306</datecreate>
<task uuid="92F7F685-C370-4E55-9026-020E3CDCEDE0" status="0">
<task_headline>TEST2000</task_headline>
<task_subject>There is a Problem.</task_subject>
<task_action>Solve it!</task_action>
<task_priority color="#E62C29">high</task_priority>
<task_status>200</task_status>
<task_note></task_note>
</task>
<task uuid="AWFWF-C510-4E52-9026-020E3BFDDSG" status="0">
<task_headline>TEST3000</task_headline>
<task_subject>Another Problem</task_subject>
<task_action>Solve it again.</task_action>
<task_priority color="#E62C29">high</task_priority>
<task_status>200</task_status>
</task>
</Test1>
What I want is: search for uuid=AWFWF-C510-4E52-9026-020E3BFDDSG and set status = 1000.
Both of them are attributes
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
String xpathexpression = "//task[#uuid=\"" + taskItems.get(position).get(task_uuid) + "]";
XPathExpression expression = xPath.compile(xpathexpression);
NodeList nl = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);
Isn't that right?
I get the uuid from a ArrayList<HashMap<String,String>>.
Maybe I do an mistake in the expression while adding the uuid from taskItems.
After I solved the Problem, how can I change the status to 1000?
Looks like you missed the closing double quotes here :
String xpathexpression = "//task[#uuid=\"" + taskItems.get(position).get(task_uuid) + "\"]";
It may be slightly more readable if you use single quotes instead :
String xpathexpression = "//task[#uuid='" + taskItems.get(position).get(task_uuid) + "']";

How to retrieve a specific node's value in XPath?

I have a XML file with this format:
<object>
<origin>1:1:1</origin>
<normal>2:2:2</normal>
<leafs>
<object>
<origin>1:1:1</origin>
<normal>3:3:3</normal>
<leafs>none</leafs>
</object>
</leafs>
</object>
How could I retrieve the value "none" of element <leafs> on second level of the tree? I used this
XPathExpression expLeafs = xpath.compile("*[name()='leafs']");
Object resLeafs = expLeafs.evaluate(node, XPathConstants.NODESET);
NodeList leafsList = (NodeList) resLeafs;
if (!leafsList.item(0).getFirstChild().getNodeValue().equals("none"))
more code...
but it doesn't work because there are some empty text nodes bofore and after "none". Is there a way to deal with it like xpath.compile("*[value()='none']")?
I just ran a simple test program using your XML file and
expr = xpath.compile("/object/leafs/object/leafs/text()");
and got the desired "none" result. If you have additional requirements, you'll have to edit your question.
After a checking the code line #Lord Torgamus provided i managed to parse the document as i needed like this:
XPathExpression expLeafs = xpath.compile("*[name()='leafs']");
Object resLeafs = expLeafs.evaluate(node, XPathConstants.NODESET);
NodeList leafsList = (NodeList) resLeafs;
Node nd = leafsList.item(0);
XPathExpression expr = xpath.compile("text()");
Object resultObj = expr.evaluate(nd, XPathConstants.NODE);
String str = expr.evaluate(nd).trim();
System.out.println(str);
and the output is "none" with no other empty text node.

Document - How to get a tag's value by its name?

I'm using Java's DOM parser to parse an XML file.
let's say I have the following XML
<?xml version="1.0"?>
<config>
<dotcms>
<endPoint>ip</endPoint>
</dotcms>
</config>
</xml>
I like to get the value of 'endPoint'. I can do it with the following code snippet. (assuming that I already parsed it with DocumentBuilder)
NodeList nodeList = this.doc.getElementByTagName("dotcms");
Node nValue = (Node) nodeList.item(0);
return nValue.getNodeValue();
Is it possible to get a value of a field by a field's name? Like....
Node nValue = nodeList.getByName("endPoint") something like this...?
You should use XPath for these sorts of tasks:
//endPoint/text()
or:
/config/dotcms/endPoint/text()
Of course Java has a built-in support for XPath:
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//endPoint/text()");
Object value = expr.evaluate(doc, XPathConstants.STRING);
You could also use jOOX, a jquery-like DOM wrapper, to write even less code:
// Using css-style selectors
String text1 = $(document).find("endPoint").text();
// Using XPath
String text2 = $(document).xpath("//endPoint").text();

Categories