How to get root node attributes on java - 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

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());

Process XML node as Independent XML Document and update the node in Original XML document

I need process a XML node as independent XML, add a new tag to the Node Document , update the original XML document with the new node info. Any help, advice or tutorial is welcome.
This is the original XML:
<ENVOLVENTE id="ENVOLVENTE">
<FirmaEmpresa>
<FirmaDonante>
<Firma>
<Relacion>
<RelacionId>32490342093249090234</RelacionId>
</Relacion>
<Formulario>
<Donante>
<DonanteNombre>Gloria Robles</DonanteNombre>
<DonanteCorreo>gloria#gmail.com</DonanteCorreo>
</Donante>
<Beneficiado>
<BeneficiarioPais>USA</BeneficiarioPais>
<BeneficiadoCorreo>usdonations#gmail.com</BeneficiadoCorreo>
</Beneficiado>
<Fabricantes>
<Fabricante>
<FabricanteNumeroOrden>1</FabricanteNumeroOrden>
<FabricantePais>MX</FabricantePais>
<FabricanteCorreo>fabricante#gmail.com</FabricanteCorreo>
</Fabricante>
</Fabricantes>
<ListaDonaciones>
<Donaciones>
<DonacionesNumeroOrden>1</DonacionesNumeroOrden>
<DonacionesProductoId>nombre</DonacionesProductoId>
<DonacionesCantidadDonada>100</DonacionesCantidadDonada>
<DonacionesFechaDonacion>2016-12-29T12:21:16</DonacionesFechaDonacion>
</Donaciones>
</ListaDonaciones>
</Formulario>
</Firma>
</FirmaDonante>
<Empresa>
<EmpresaPais>MX</EmpresaPais>
<EmpresaNombre>Donaciones A.C </EmpresaNombre>
<EmpresaDirecccion>AV. REFORMA 1900</EmpresaDirecccion>
<EmpresaCiudad>CDXM</EmpresaCiudad>
</Empresa>
<PermisoEmpresa>
<PermisoNumero>329023409324902349023409234</PermisoNumero>
</PermisoEmpresa>
</FirmaEmpresa>
</ENVOLVENTE>
Now, i need extract the node "FirmaDonante" to a new XML DOM:
<FirmaDonante>
<Firma>
<Relacion>
<RelacionId>32490342093249090234</RelacionId>
</Relacion>
<Formulario>
<Donante>
<DonanteNombre>Gloria Robles</DonanteNombre>
<DonanteCorreo>gloria#gmail.com</DonanteCorreo>
</Donante>
<Beneficiado>
<BeneficiarioPais>USA</BeneficiarioPais>
<BeneficiadoCorreo>usdonations#gmail.com</BeneficiadoCorreo>
</Beneficiado>
<Fabricantes>
<Fabricante>
<FabricanteNumeroOrden>1</FabricanteNumeroOrden>
<FabricantePais>MX</FabricantePais>
<FabricanteCorreo>fabricante#gmail.com</FabricanteCorreo>
</Fabricante>
</Fabricantes>
<ListaDonaciones>
<Donaciones>
<DonacionesNumeroOrden>1</DonacionesNumeroOrden>
<DonacionesProductoId>nombre</DonacionesProductoId>
<DonacionesCantidadDonada>100</DonacionesCantidadDonada>
<DonacionesFechaDonacion>2016-12-29T12:21:16</DonacionesFechaDonacion>
</Donaciones>
</ListaDonaciones>
</Formulario>
</Firma>
</FirmaDonante>
After that, I will modify the node as new XML document, something like that, with a new XML Element after the original Node.
<FirmaDonante>
<Firma>
<Relacion>
<RelacionId>32490342093249090234</RelacionId>
</Relacion>
<Formulario>
<Donante>
<DonanteNombre>Gloria Robles</DonanteNombre>
<DonanteCorreo>gloria#gmail.com</DonanteCorreo>
</Donante>
<Beneficiado>
<BeneficiarioPais>USA</BeneficiarioPais>
<BeneficiadoCorreo>usdonations#gmail.com</BeneficiadoCorreo>
</Beneficiado>
<Fabricantes>
<Fabricante>
<FabricanteNumeroOrden>1</FabricanteNumeroOrden>
<FabricantePais>MX</FabricantePais>
<FabricanteCorreo>fabricante#gmail.com</FabricanteCorreo>
</Fabricante>
</Fabricantes>
<ListaDonaciones>
<Donaciones>
<DonacionesNumeroOrden>1</DonacionesNumeroOrden>
<DonacionesProductoId>nombre</DonacionesProductoId>
<DonacionesCantidadDonada>100</DonacionesCantidadDonada>
<DonacionesFechaDonacion>2016-12-29T12:21:16</DonacionesFechaDonacion>
</Donaciones>
</ListaDonaciones>
</Formulario>
</Firma>
</FirmaDonante>
<Signature>
<SignedInfo/>
<KeyInfo/>
</Signature>
Finally, i need add the Node document in the same position in the original document, as Node, with the new tag:
<ENVOLVENTE id="ENVOLVENTE">
<FirmaEmpresa>
<FirmaDonante>
<Firma>
<Relacion>
<RelacionId>32490342093249090234</RelacionId>
</Relacion>
<Formulario>
<Donante>
<DonanteNombre>Gloria Robles</DonanteNombre>
<DonanteCorreo>gloria#gmail.com</DonanteCorreo>
</Donante>
<Beneficiado>
<BeneficiarioPais>USA</BeneficiarioPais>
<BeneficiadoCorreo>usdonations#gmail.com</BeneficiadoCorreo>
</Beneficiado>
<Fabricantes>
<Fabricante>
<FabricanteNumeroOrden>1</FabricanteNumeroOrden>
<FabricantePais>MX</FabricantePais>
<FabricanteCorreo>fabricante#gmail.com</FabricanteCorreo>
</Fabricante>
</Fabricantes>
<ListaDonaciones>
<Donaciones>
<DonacionesNumeroOrden>1</DonacionesNumeroOrden>
<DonacionesProductoId>nombre</DonacionesProductoId>
<DonacionesCantidadDonada>100</DonacionesCantidadDonada>
<DonacionesFechaDonacion>2016-12-29T12:21:16</DonacionesFechaDonacion>
</Donaciones>
</ListaDonaciones>
</Formulario>
</Firma>
</FirmaDonante>
<!--NEW TAG -->
<Signature>
<SignedInfo/>
<KeyInfo/>
</Signature>
<!--NEW TAG -->
<Empresa>
<EmpresaPais>MX</EmpresaPais>
<EmpresaNombre>Donaciones A.C </EmpresaNombre>
<EmpresaDirecccion>AV. REFORMA 1900</EmpresaDirecccion>
<EmpresaCiudad>CDXM</EmpresaCiudad>
</Empresa>
<PermisoEmpresa>
<PermisoNumero>329023409324902349023409234</PermisoNumero>
</PermisoEmpresa>
</FirmaEmpresa>
</ENVOLVENTE>
actually, i can extract the Node, but i have errors when i try to add a new Element the node document:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(
xmlFile.getBytes(StandardCharsets.UTF_8));
Document document = builder.parse(stream);
Element elementFirmaDonante = (Element) document.getElementsByTagName("FirmaDonante").item(0);
DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
Document documentoCODExporterMasEH = documentBuilder.newDocument();
Node newNode = documentoCODExporterMasEH.importNode(elementFirmaDonante, true);
documentoCODExporterMasEH.appendChild(newNode);
/*In this point all is OK, a can serialize de Document, but now, a can't add a new Item to the node document*/
/*
* This block, throws error:
* HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
*/
Element anotherElement = (Element) document.getElementsByTagName("Empresa").item(0);
Node anotherNewNode = documentoCODExporterMasEH.importNode(anotherElement, true);
documentoCODExporterMasEH.insertBefore(anotherNewNode, newNode);
The above code is just to test that I can add new Elements or nodes to the DOM Object.
Any suggestions ??
Thanks in advance!!!!!
See the below code, I am able to insert a new node before Empresa node:-
Element anotherElement = (Element)document.getElementsByTagName("Empresa").item(0);
Element newTag = document.createElement("Signature");
Element childElem1=document.createElement("SignedInfo");
Element childElem2=document.createElement("KeyInfo");
newTag.appendChild(childElem1);newTag.appendChild(childElem2);
anotherElement.getParentNode().insertBefore(newTag, anotherElement);
Try to change your code like below:-
documentoCODExporterMasEH.insertBefore(newNode,anotherNewNode);

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.)

how to get a node value in Xpath - Java

I've got a section of XML that looks like this:
<entry>
<id>tag:example.com,2005:Release/343597</id>
<published>2012-04-10T11:29:19Z</published>
<updated>2012-04-10T12:04:41Z</updated>
<link type="text/html" href="http://example.com/projects/example1" rel="alternate"/>
<title>example1</title>
</entry>
I need to grab the link http://example.com/projects/example1 from this block. I'm not sure how to do this. To get the title of the project I use this code:
String title1 = children.item(9).getFirstChild().getNodeValue();
where children is the getChildNodes() object for the <entry> </entry> block. But I keep getting NullPointerExceptions when I try to get the node value for the <link> node in a similar way. I see that the XML code is different for the <link> node, and I'm not sure what it's value is.... Please advise!
The xpath expression to get that node is
//entry/link/#href
In java you can write
Document doc = ... // your XML document
XPathExpression xp = XPathFactory.newInstance().newXPath().compile("//entry/link/#href");
String href = xp.evaluate(doc);
Then if you need to get the link value of the entry with a specific id you can change the xpath expression to
//entry[id='tag:example.com,2005:Release/343597']/link/#href
Finally if you want to get all the links in the documents, if the document has many entry elements you can write
Document doc = ... // your XML document
XPathExpression xp = XPathFactory.newInstance().newXPath().compile("//entry/link/#href");
NodeList links = (NodeList) xp.evaluate(doc, XPathConstants.NODESET);
// and iterate on links
Here is the complete code:
DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("test.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//entry/link/#href");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i));
}

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()

Categories