how remove XML Node with java - java

i need to remove the "Object" tag, but I need to preserve and keep the content. Is that possible?
<ds:KeyInfo>
<wsse:SecurityTokenReference>
<wsse:Reference URI="#b3f74c53-b79f-4dec-aa26-ca552f8f8745"/>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
<ds:Object Id="id1"> // <-Remove this
<wsu:Timestamp>
<wsu:Created>2017-03-28T20:21:44Z</wsu:Created>
<wsu:Expires>2017-03-28T23:08:24Z</wsu:Expires>
</wsu:Timestamp>
</ds:Object> // <-Remove this
I tried:
Node node = xml.getElementById("id1");
xml.getDocumentElement().removeChild(node);
but:
Org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.

First of all, only the parent of the node to be removed can remove it:
Node nodeToBeRemoved = xmlDoc.getElementById("id1");
Node parentNode = nodeToBeRemoved.getParentNode();
Node removedNode = parentNode.removeChild(nodeToBeRemoved);
Second, in order to "preserve and keep the content" you will need to attach the children elements of the removed one to its parent:
NodeList removedChildren = removedNode.getChildNodes();
for (int i = 0 ; i < removedChildren.getLength(); i++) {
Node child = removedChildren.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
parentNode.appendChild(child);
}
}

Related

Add a node in xml using java only if the node has an attribute

I have the following xml code and I want to add a note in node manufacturedMaterial only if it has the attribute determinerCode.
<manufacturedProduct classCode="MANU">
<manufacturedMaterial classCode="MMAT" determinerCode="KIND">
<code code="10219000" codeSystem="0.4.0.127.0.16.1.1.2.1" codeSystemName="EDQM" codeSystemVersion="2017-04-14" displayName="Tablet"/>
</epsos:code>
</manufacturedMaterial>
<manufacturedMaterial classCode="MMAT">
<code code="10219001" codeSystem="0.4.0.127.0.16.1.1.2.2" codeSystemName="EDQM" codeSystemVersion="2017-04-14" displayName="NoTablet"/>
</epsos:code>
</manufacturedMaterial>
</manufacturedProduct>
Currently, my code is the following, but add a new child in both manufacturedMaterial nodes. Is there a way to check whether it has the attribute determinerCode or not?
NodeList nodes = dom.getElementsByTagName("manufacturedMaterial");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
NodeList childNodes = node.getChildNodes();
Element formCodeEl = dom.createElement("epsos:formCode");
formCodeEl.setAttribute("code", myCode.get(i));
node.appendChild(formCodeEl);
}
Can you check the list of attributes in the node?
if(node.getAttributes().getNamedItem("determinerCode") != null)
{
// Add your node here...
}

Couldn't able to read the attribute using DOM parser

i am having issues when reading the attribute of a link,
this is the structure of my xml,
<entry>
<updated>
<title>
<link href="">
</entry>
i managed to read the date and title correctly but the href attribute of the link is not working.
Here is my code,
NodeList nList = doc.getElementsByTagName("entry");
System.out.println("============================");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node node = nList.item(temp);
System.out.println(""); //Just a separator
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
System.out.println("Date : " + eElement.getElementsByTagName("updated").item(0).getTextContent());
System.out.println("Title : " + eElement.getElementsByTagName("title").item(0).getTextContent());
// The below code is for reading href attribute of link,
NodeList node1 = eElement.getElementsByTagName("link");
Element eElement1 = (Element) node1;
System.out.println(eElement1.getAttribute("href"));
}
}
I am creating a new nodelist for the attributes of link but the code is not working.
error:
java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl cannot be cast to org.w3c.dom.Element
at Demo.main(Demo.java:45)
A NodeList is not an Element and cannot be cast to one (successfully), so this code isn't going to work:
NodeList node1 = eElement.getElementsByTagName("link");
Element eElement1 = (Element) node1;
A NodeList is, as the name suggests, a list of nodes (and in your case, the nodes will be Elements). So this code would work for the first link:
NodeList list = eElement.getElementsByTagName("link");
Element eElement1 = (Element) list.item(0);
...whereupon your getAttribute should work fine, as Element has getAttribute.
Side note: If your library has support for newer query functions, you could also do this:
String href = ((Element)eElement.querySelector("entry")).getAttribute("href");
...because querySelector returns just the first match (not a list) (or null if no matches; if that's a possibility, add a guard to the above). But I don't know how well querySelector is supported outside of browsers yet.
// The below code is for reading href attribute of link,
NodeList node1 = eElement.getElementsByTagName("link");
Element eElement1 = (Element) node1;
NodeList will give you Node object not Element, you can get href value as follows,
String hrefValue = nodeList.item(0).
getAttributes().getNamedItem("href").getNodeValue();

java Convert Element to string

I am looking to get only the tag name, and not it's children.
I have an xml like this:
<RESPONSE>
<RESULT> !--TableName
<ADDRESS1>123 Main Street</ADDRESS1> !--ColumnName
<ZIP>12345</ZIP> !--ColumnName
</RESULT>
<RESULT> !--TableName
<ADDRESS1>245 Elm Street</ADDRESS1> !--ColumnName
<ZIP>45678</ZIP> !--ColumnName
</RESULT>
<VIN> !--TableName
<VIN_NUM>1K45678RTW23</VIN> !--ColumnName
</VIN>
….
</REPSONSE>
I am trying to dynamically save the xml into it's appropriate table and column names. So, I want to extract whatever the first element is, and assign it to a table name variable, and then it's children as columns.
Here is what I am doing so far:
private void extractToTableSet(Document doc, int appseqno ) throws Exception
{
NodeList responseList = doc.getElementsByTagName("RESPONSE");
for (int i = 0; i < responseList.getLength(); i++) {
Node currentNode = responseList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element tableElement = (Element) responseList.item(i);
if (tableElement != null && tableElement.hasChildNodes()) {
for (columnNode = tableElement.getFirstChild(); columnNode != null; columnNode = columnNode.getNextSibling()) {
if (columnNode.getNodeType() == Node.TEXT_NODE) {
columnName = columnNode.getNodeValue;
}
}
}
}
}
}
This way I am only able to get the values in the child nodes. Is there a way to get the name of the Element tags? Like I want to extract the value RESULT from the Document object.
In DOM, an element name is retrieved using Node.getNodeName().
Example:
if(node.getNodeType() == Node.ELEMENT_NODE) {
String elementName = node.getNodeName();
...
}
To get element's tagname :
Element tableElement = (Element) responseList.item(i);
String tagname = tableElement .getTagName();

Casting node to element giving ClassCastException

here n2 is my NodeList, and i just want to see the first child node of my root element
public void ClickMe(View view){
Node rootElement=n2.item(0);
NodeList child=rootElement.getChildNodes();
Node first=child.item(0);
//ClassCastException error is coming whenever i am casting first to Element.
Element nm=(Element)first;
Option q= getOption(nm,first);
Log.i(TAG,"the name is was talking about is : "+ q.getName());
}
this what logcat says
07-31 20:32:38.376: E/AndroidRuntime(2950): Caused by: java.lang.ClassCastException: org.apache.harmony.xml.dom.TextImpl cannot be cast to org.w3c.dom.Element
Try it like this....
NodeList LOP = odoc.getElementsByTagName("Your_XML_Top_Element");
Node FPN =LOP.item(0);
try{
if(FPN.getNodeType() == Node.ELEMENT_NODE)
{
Element token = (Element)FPN;
NodeList oNameList1 = token.getElementsByTagName("Your_XML_Sub_Node");
Element firstNameElement = (Element)oNameList1.item(0);
NodeList textNList1 = firstNameElement.getChildNodes();
}
If node is element then only cast it. Make check like below.
if (first.getNodeType() == Node.ELEMENT_NODE) { Element nm=(Element)first;}

Child elements of DOM

I have this XML file:
<scene>
<texture file="file1.dds"/>
<texture file="file2.dds"/>
...
<node name="cube">
<texture name="stone" unit="0" sampler="anisotropic"/>
</node>
</scene>
I need all child element of 'scene' that are named "texture", but with this code:
Element rootNode = document.getDocumentElement();
NodeList childNodes = rootNode.getElementsByTagName("texture");
for (int nodeIx = 0; nodeIx < childNodes.getLength(); nodeIx++) {
Node node = childNodes.item(nodeIx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
// cool stuff here
}
}
i also get the 'texture' elements which are inside 'node'.
How can i filter these out? Or how can i get only the elements that are direct childs of 'scene'?
You can do it using Xpath, consider the following example taken from the JAXP Specification 1.4 (which I recommend you to consult for this):
// parse the XML as a W3C Document
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
org.w3c.Document document = builder.parse(new File("/widgets.xml"));
// evaluate the XPath expression against the Document
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/widgets/widget[#name='a']/#quantity";
Double quantity = (Double) xpath.evaluate(expression, document, XPathConstants.NUMBER);
I found myself a solution that works fine:
Element parent = ... ;
String childName = "texture";
NodeList childs = parent.getChildNodes();
for (int nodeIx = 0; nodeIx < childs.getLength(); nodeIx++) {
Node node = childs.item(nodeIx);
if (node.getNodeType() == Node.ELEMENT_NODE
&& node.getNodeName().equals(name)) {
// cool stuff here
}
}

Categories

Resources