How to get XML content as a String - java

<root>
<h id="1">
<d value="1,2,3,4,5"><open>10:00</open><close>23:00</close></d>
<d value="6"><open>10:00</open><close>2:00</close></d>
<d value="7"><open>10:00</open><close>21:00</close></d>
</h>
<h id="2">
</h>
</root>
Here I have the XML which root has list of <h> tagged nodes. Now I need to break these into parts and set it into different variables (add into a map).
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(data.getBytes("utf-8"))));
NodeList nList = doc.getElementsByTagName("h");
for (int i = 0; i < nList.getLength(); i++)
{
Node nNode = nList.item(i);
System.out.println(nNode.getAttributes().getNamedItem("id") + " " + ?????);
}
what should I call in order to get the value (String value) of a nNode ?
Here is what Im looking for as the asnwer for the above code once some one fills the ????
1 <h id="1"><d value="1,2,3,4,5"><open>10:00</open><close>23:00</close></d><d value="6">open>10:00</open><close>2:00</close></d><d value="7"><open>10:00</open><close>21:00</close></d></h>
2 <h id="2"></h>
And i don't mind having as root element

You can use Node.getTextContent() to conveniently get all the text of a node (gets text of children as well).
See Parsing xml file contents without knowing xml file structure for a short example.
If you're trying to get the value attributes of the d nodes (I can't actually tell, your question is slightly unclear to me), then it would be different -- for that you would iterate through the children of each h node (use getChildNodes() or getFirstChild() + getNextSibling()) then grab their value attributes just as you are getting the id attribute of the h nodes (the above link also shows an example of iterating through child nodes).

Have you tried jDom library? http://www.jdom.org/docs/apidocs/org/jdom2/output/XMLOutputter.html
XMLOutputter outp = new XMLOutputter();
String s = outp.outputString(your_jdom_element);

Have you tried nNode.toString() if you are using Node from javax.xml.soap.Node.

You can use that:
http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html#getTextContent()
but your sample nNode has other nodes, not just text. It seems you need helper method to construct String from child nodes.
Pass your nNode to nodeToString
XML Node to String in Java

Related

How to extract data from <dc> tag in java?

I am currently trying to extract the tag element < dc:title > from an epub in Java. However, i tried using
doc.getDocumentElement().getElementsByTagName("dc:title"));
and it only showed 2nd element :com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl. I would like to know how can I extract < dc:tittle > ?
Here is my code:
File fXmlFile = new File("file directory");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("1st element :" + doc.getElementsByTagName("dc");
System.out.println("2nd element :" + doc.getDocumentElement().getElementsByTagName("dc:title"));
System output:
1st element : com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl#4f53e9be
2nd element :com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl#e16e1a2
Added Sample Data
<dc:title>
<![CDATA[someData]]>
</dc:title>
<dc:creator>
<![CDATA[someData]>
</dc:creator>
<dc:language>someData</dc:language>
The method getElementsByTagName(String) is return a List of matching elements (note plural 's'). You then need to specify which element (such as by using .item(index) to access a Node instance) you want to use. Therewith, you can using getNodeValue() on that Node object.
EDITED: because of the CDATA element, rather use Node.getTextContent():
NodeList elems = doc.getElementsByTagName("dc:title");
Node item = elems.item(0);
System.out.println(item.getTextContent());
I would suggest using xpath to get the desired output.
Also, refer following link for examples.
https://www.journaldev.com/1194/java-xpath-example-tutorial
For example:
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//dc:title/text()";
NodeList nodes = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
System.out.println(nodes.item(0).getNodeValue());

Xpath insert sequence of nodes under a node - Java

I am trying to add sequence of nodes under a node, below is my reference xml:
<?xml version="1.0" encoding="UTF-8"?>
<transformation>
<info>
<name>Bulkload</name>
<description/>
<extended_description/>
<trans_version/>
<trans_type>Normal</trans_type>
<trans_status>0</trans_status>
<directory>/</directory>
</info>
<connection>
<name>con_name</name>
<server>server</server>
<type>SYBASE</type>
<access>Native</access>
<database>database</database>
<port>port</port>
<username>user</username>
<password>Encrypted xyz</password>
</connection>
<step>
<name>Extract</name>
<type>TextFileOutput</type>
<fields>
**HERE**
<field>
</field>
</fields>
<cluster_schema/>
<remotesteps> <input> </input> <output> </output> </remotesteps> <GUI>
<xloc>300</xloc>
<yloc>168</yloc>
<draw>Y</draw>
</GUI>
</step>
</transformation>
I want to add below xml block inside field tag:
<field>
<name>field_name</name>
<type>Integer</type>
<format>#;-#</format>
<currency/>
<decimal>.</decimal>
<group>,</group>
<nullif/>
<trim_type>none</trim_type>
<length>9</length>
<precision>0</precision>
</field>
My requirement is to create new xml documents from the above template. I only found a method in Xpath to insert node before a node so I updated my template and added a blank field node in it inside fields node and with that I was able to insert a node with the below code:
File dest =new File("H:\\Project_Documents\\reference.ktr");
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setIgnoringComments(true);
DocumentBuilder builder = factory.newDocumentBuilder();
String newLine = System.getProperty("line.separator");
Document document = builder.parse(dest);
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
NodeList nodes = document.getElementsByTagName("field");
Text a = document.createTextNode("Anup");
Element p =document.createElement("field");
p.appendChild(a);
nodes.item(0).getParentNode().insertBefore(p, nodes.item(0));
but again I faced the dame problem for child nodes i.e name, type, format, etc. Could anybody please show me a way to achieve my purpose?
If I cannot achieve it with Xpath then which parser I should use?
One solution, which works:
You have to manage two XML Documents, find the tag you want, and replace.
With XPath you can select more precisely, but no use there.
1 get a DOM for your global XML
Document document= ...
2 get the node you want to insert
Document document_to_insert = builder.parse(new InputSource(new StringReader(xml_to_insert))); // ...
//GET NODE field
NodeList nodes_field_to_insert=document_to_insert.getElementsByTagName("field");
Element node_field_to_insert=null;
for(int i=0; i<nodes_field_to_insert.getLength(); i++)
{
Node the_node = nodes_field_to_insert.item(i);
// WE TAKE THE FIRST ONE
if(the_node instanceof Element)
{
node_field_to_insert=(Element) the_node;
break;
}
}
3 go to the field node in the global XML
4 replace inside the node
// GET NODE field
NodeList nodes=document.getElementsByTagName("field");
for(int i=0; i<nodes.getLength(); i++)
{
Node the_node = nodes.item(i);
if(the_node instanceof Element)
{
Element a_child = (Element) the_node;
Node newNode = document.importNode(node_field_to_insert, true);
// FATHER
Node the_parent=a_child.getParentNode();
the_parent.replaceChild(newNode,a_child);
// WE STOP
break;
}
}

How do I get the tag 'Name' from a XML Node in Java (Android)

I have a tiny little problem parsing an XML file in Java (Android).
I have an XML file that is like this:
<Events>
<Event Name="Olympus Has Fallen">
...
</Event>
<Event Name="Iron Man 3">
...
</Event>
</Events>
I already managed to get the NodeList by doing this:
URL url = new URL("********");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("Event");
Also I managed to get every single item of the NodeList by doing this:
for (int i = 0; i < nodeList.getLength(); i++) {
// Item
Node node = nodeList.item(i);
Log.i("film", node.getNodeName());
}
But this just Logs: "Event" instead of the value of the Name tag.
How do I output the value of this 'name' tag from the XML.
Can anyone help me with this one?
Thanks in advance!
But this just Logs: "Event" instead of the value of the Name tag.
Yes, because you're asking for the name of the element. There isn't a Name "tag" - there's a Name attribute, and that's what you should find:
// Only check in elements, and only those which actually have attributes.
if (node.hasAttributes()) {
NamedNodeMap attributes = node.getAttributes();
Node nameAttribute = attributes.getNamedItem("Name");
if (nameAttribute != null) {
System.out.println("Name attribute: " + nameAttribute.getTextContent());
}
}
(It's very important to be precise in terminology - it's worth knowing the difference between nodes, elements, attributes etc. It will help you enormously both when communicating with others and when looking for the right bits of API to call.)

Get an attribute of a dom node

I am trying to get an attribute of an xml node example:
<Car name="Test">
</Car>
I want to grab the name attribute of the car node.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(configFile);
doc.getDocumentElement().normalize();
NodeList layerConfigList = doc.getElementsByTagName("CAR");
Node node = layerConfigList.item(0);
// get the name attribute out of the node.
this is where i get stuck because the only method that looks like i can use is getAttributes() with returns a NamedNodeMap and im not sure how to extract it from that.
Your node is an Element so you just have to
Element e = (Element)node;
String name = e.getAttribute("name");
you can do it without using elements, like this:
//HtmlTag represents any arbitrary node that you are trying to get its "car" attribute
if("HtmlTag".equals(node.getNodeName()))
String nodeContent=node.getAttributes().getNamedItem("car").getNodeValue()

How to get root node attributes on java

I have an xml file like down below. I want to get pharmacies nodes' latitude and longitude attributes.I can get chilnodes attributes but couldnt get root node attributes. I am new on java and xml. I could not find a solution how to do.
<pharmacies Acc="4" latitude="36.8673380" longitude="30.6346640" address="Ayujkila">
<pharmacy name="sadde" owner="" address="dedes" distance="327.000555668" phone="342343" lat="36.8644" long="30.6345" accuracy="8"/>
<pharmacy name="Sun " owner="" address="degerse" distance="364.450016586" phone="45623" lat="36.8641" long="30.6353" accuracy="8"/>
<pharmacy name="lara" owner="" address="freacde" distance="927.262190129" phone="564667" lat="36.8731" long="30.6422" accuracy="8"
<end/>
</pharmacies>
This is my part of code. I get xml file from a url address.
DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList =doc.getElementsByTagName("pharmacy");
for (int i = 0; i < nodeList.getLength(); i++){
Node node =nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList pharmacyList = fstElmnt.getElementsByTagName("pharmacy");
Element pharmacyElement = (Element) pharmacyList.item(0);
Element pharmacyElement = (Element) pharmacyList.item(0);
HashMap<String,String>map=new HashMap<String,String>();
map.put("name", pharmacyElement.getAttribute("name"));
map.put("distance", pharmacyElement.getAttribute("phone"));
list.add(map);
latt.add(pharmacyElement.getAttribute("lat"));
....
The <pharmacies> element itself can be obtained using
Element pharmacies = doc.getDocumentElement();
You can get the attributes from that.
doc.getDocumentElement() will return the root element and you can call getAttribute( attrName ) on it like you would on any other element.
try the following:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
doc.getDocumentElement().normalize();
System.out.println(doc.getChildNodes().getLength());
Node item = doc.getChildNodes().item(0);
System.out.println(item.getNodeName());
Node lat = item.getAttributes().getNamedItem("latitude");
String s = lat.getNodeValue();
System.out.println(s.equals("36.8673380")); // Value of /pharmacies[#latitude]/value()
You need to use pharmacies instead of pharmacy if you need to get attributes for root node pharmacies.And use getAttributes method instead.You can see lot of examples at this site.
http://java.sun.com/developer/codesamples/xml.html#dom
Try Its Work For me, Res is your final String:
doc = b.parse(new ByteArrayInputStream(result.getBytes("UTF-8")));
Node rootNode=doc.getDocumentElement();
res = rootNode.getNodeName().toString();
The <pharmacies> is itself an element & can be obtained using
Element pharmacies = doc.getDocumentElement();
Now this pharmacies reference variable of Elements holds all the attributes under <pharmacies> element. We can get desired attributes one by one using attribute name like :
pharmacies.getAttribute("latitude"); // Will give 36.8673380
pharmacies.getAttribute("longitude"); // Will give 30.6346640

Categories