Getting parent node content in xml file by java - java

In XML file a Parent tag has multiple child tag, with content inside.
I need the Parent tag info only,
how to get that:
i.e.,
<main>**Name**
<names>**Harish**</names>
<names2>**Mathi**</names>
</main>
Here i need only "Name". I no need "Harish","Mathi"...
in this case what i have to include in JAVA code...

You can do using XPath:
main/text()
UPDATE:
Example:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("sample.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("main/text()");
Object result = expr.evaluate(doc, XPathConstants.STRING);
System.out.println(result.toString());
OUTPUT:
**Name**

Related

Why does Document object not need to be cast when passing to XPathExpression.evalutate method?

I'm doing some work cleaning up working code in an application of mine, and I noticed that I was reusing XPathFactory, XPath, XPathExpression objects in multiple places in my code, and figured I would clean it up and set up a method to do this. What I noticed is that typically when you send the XML document to the XPathExpression.evalutate method that you just place it in the parameter for the source like this.
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
Document builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new FileReader("/path/to/file.xml"));
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expression = xpath.compile("path/to/node");
Object result = expression.evaluate(document, XPathConstants.NODE);
This is fine that it works but when I try to wrap the XPath portion into a separate method like this:
private Object getObjectByExpression(String expr, InputSource source, QName objectType)
{
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expression = xpath.compile(expr);
Object result = expression.evaluate(document, objectType);
return result;
}
public void someCalledMethod()
{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
Document builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new FileReader("/path/to/file.xml"));
Object result = getObjectByExpression("/path/to/node", document, XPathConstants.NODE);
}
Eclipse tells me that I must cast the document to InputSource and marks it as an error. I did double check that the InputSource used in XPathExpression.evaluate and that in my method are the same class type. Does anyone have a deeper understanding as from where this inconsistency comes?
Actually, with Document it is using XPathExpression.evaluate(Object, QName) method.
Document is an interface, so it can't heritate the class InputSource. It is not possible. This is why you need to update your method :
private Object getObjectByExpression(String expr, Object source, QName objectType)
Or if you really want to limit this to Document
private Object getObjectByExpression(String expr, Document source, QName objectType)

Add XML String as Node to Existing XML

I have an xml/mathml fragment in string like <msup><mn>2</mn><mn>6</mn></msup><mo>+</mo><msup><mn>2</mn><mn>7</mn></msup>
I want to replace an existing xml node with this string. I tried
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuild = docFactory.newDocumentBuilder();
Document doc = docBuild.parse(is); //is ==> Inputstream
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new Namespace());
XPathExpression expr = xpath.compile(xPath); //xPath ==>XPath of parent node where the above is to be appended
Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
if (node.getChildNodes().item(0).getNodeName().equals("mml:math")) {
node.removeChild((node.getChildNodes().item(0)));
Element s= doc.createElement("mml:math");
s.setNodeValue("<msup><mn>2</mn><mn>6</mn></msup><mo>+</mo><msup><mn>2</mn><mn>7</mn></msup>");
node.appendChild(s);
}
Instead of using s.setNodeValue(), I used s.setTextContent() which fixed my problem.

use xpath to extract value from xml file with multiple namespace in java

I am trying to extract node value with multiple namespaces in java but not succeed. The xml file is like:
<ns26:start xmlns:ns26="http://www.tektronix.com/iris/isa/capture/start"
xmlns:ns31="http://www.tektronix.com/iris/isa/filters"
xmlns:ns13="http://www.tektronix.com/iris/isa/monitoredObjects"
xmlns:ns6="http://www.tektronix.com/iris/isa"
xmlns:ns10="http://www.tektronix.com/iris/isa/monNodeObjects"
xmlns:ns7="http://www.tektronix.com/iris/isa/capture/monitoredElements"
xmlns:ns11="http://www.tektronix.com/iris/isa/pointcodes"
xmlns:ns8="http://www.tektronix.com/iris/isa/capture/captureSession"
xmlns:ns2="http://www.tektronix.com/iris/isa/sessionSaveInfo"
xmlns:ns4="http://www.tektronix.com/iris/isa/customData"
xmlns:ns3="http://www.tektronix.com/iris/isa/manifest">
<ns6:Id>LAB:11300/isaclient;440</ns6:Id>
</ns26:start>
I want to extract Id with xpath local-name(). Expression like //*[local-name()='start']/*[local-name()='Id'] but didn't get any matched node. Please help to find issue here. Thanks
Add the java code here:
public static List<String> getXPathValueNamespace(String xml, String expression throws ParserConfigurationException, SAXException, IOException, XPathExpressionException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
List<String> list = new ArrayList<String>();
builder = factory.newDocumentBuilder();
InputSource source = new InputSource(new StringReader(xml));
doc = builder.parse(source);
// Create XPathFactory object
XPathFactory xpathFactory = XPathFactory.newInstance();
// Create XPath object
XPath xpath = xpathFactory.newXPath();
XPathExpression expr = xpath.compile(expression);
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++)
list.add(nodes.item(i).getNodeValue());
return list;
}
The expression //*[local-name()='start']/*[local-name()='Id'] works and for the example document one node should be contained in the result node list.
But you should use nodes.item(i).getTextContent() to retrieve the node content, since getNodeValue() returns null for element nodes.

Parsing XML using XPath in Java using Google Geocode

kohaNimi = "Tallinn";
URL myUrl = new URL("http://maps.googleapis.com/maps/api/geocode/xml?address=" + kohaNimi + "&sensor=false");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(myUrl.openStream());
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/GeocodeResponse/result/bounds/southwest/lat");
String swLat = expr.evaluate(doc, XPathConstants.STRING).toString();
System.out.println("swLat: " + swLat );
So I am trying to use Google geocode API to get the coordinates of a town, but I have trouble parsing the xml. I am trying to use xPath with Java. I can verify that ... does exist. The problem is that when I try to parse this xml I wont get any text as response. I have looked over the code and can't seem to figure out what is wrong. I used this blogpost to assemble my code: http://tunatore.wordpress.com/2011/05/20/how-to-use-xpath-i-java-simple-example/
You can verify that xpath is correct(should get response) from here: http://maps.googleapis.com/maps/api/geocode/xml?address=Tallinn&sensor=false
Can anyone spot what is wrong?
Change:
xpath.compile("/GeocodeResponse/result/bounds/southwest/lat")
To:
xpath.compile("/GeocodeResponse/result/geometry/bounds/southwest/lat")

xml search element by id

Can we search a element by id in xml file using dom parser, for example :
<root>
<context id="one">
<entity>
<identifier>new one</identifier>
</entity>
</context>
<context id="two">
<entity>
<identifier>second one</identifier>
</entity>
</context>
</root>
I want a node with id = "one", my code
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("filename.xml"));
Element ele = document.getElementById("one");
return null,
is there any other way?
From the documentation for Document.getElementById
Note: Attributes with the name "ID" or "id" are not of type ID unless so defined.
The problem is the Document doesn't know that an attribute called id is an identifier unless you tell it. You need to set a schema on the DocumentBuilderFactory before you call newDocumentBuilder. That way the DocumentBuilder will be aware of the element types.
In the schema you will need something like this in the appropriate place:
<xs:attribute name="id" type="xs:ID"/>
You could use the javax.xml.xpath APIs in the JDK/JRE to find the element by XPath.
Example
import java.io.File;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("filename.xml"));
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
Element element = (Element) xpath.evaluate("//*[#id='one']", document, XPathConstants.NODE);
}
}
You could instead use a third party library like Jsoup that does the job rather quite well.
File input = new File("/tmp/input.xml");
Document doc = Jsoup.parse(input, "UTF-8", "test");
And then you could use something like this:
doc.select("context#id=one")
Does that answer your question?
try and use XML - Xpath expression it is very easy
File fXmlFile = new File("filePath");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
String expression;
Node node;
// 1. elements with id '1'
expression = "//context[#id='one']";
node = (Node ) xpath.evaluate(expression, doc, XPathConstants.NODE);

Categories