Get an attribute of a dom node - java

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

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 to get XML content as a String

<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

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