Creating xml using DOM in java - java

I am trying to create a an XML with multiple elements. Below is the code i am trying.
Element root = doc.createElement("root");
doc.appendChild(root);
Element member = doc.createElement("member");
root.appendChild(member);
Element name = doc.createElement("name");
name.appendChild(doc.createTextNode("xxx"));
member.appendChild(name);
Element phone = doc.createElement("phone");
phone.appendChild(doc.createTextNode("vvvv"));
member.appendChild(phone);
Element sss = doc.createElement("somethingNew");
root.appendChild(sss);
Element nnn = doc.createElement("name1");
nnn.appendChild(doc.createTextNode("AAA"));
sss.appendChild(nnn);
Element ppp = doc.createElement("phoneEx");
ppp.appendChild(doc.createTextNode("cc"));
sss.appendChild(ppp);
And the output i am getting is
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<member>
<name>xxx</name>
<phone>vvvv</phone>
<name>xxx</name>
<phone>vvvv</phone>
</member>
<somethingNew/>
</root>
But i am expecting somthing like Below, Please help me where i am going wriong
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<member>
<name>xxx</name>
<phone>vvvv</phone>
<name>xxx</name>
<phone>vvvv</phone>
</member>
<somethingNew>
<name1>DDD</name1>
<phoneEx>CC</phoneEx>
</somethingNew>
</root>

Never Mind i could able to find the solution, I am appending to the first element all the time, That was the issue.Corrected my code

Related

Added redundant empty NameSpace while adding newly created element in somewhere middle of the xml document in java dom4j

I have xml template like this:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="..." xmlns:xsi="..." xsi:schemaLocation="...">
<body>
<content id="unique_id1">
</content>
<content id="unique_id2">
</content>
</body>
</root>
What I want to achieve is I want to insert new elements inside content tag by finding them by corresponding id.
Such as:
Element element = doc.selectSingleNode(//*[#id='unique_id2']");
Element newElement = DocumentHelper.createElement("new-element");
newElement.addText("new element text");
element.add(newElement);
This code can insert the newElement inside the specific element. But in newElement, a blank namespace is added automatically.
After insertion, the xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="..." xmlns:xsi="..." xsi:schemaLocation="...">
<body>
<content id="unique_id1">
</content>
<content id="unique_id2">
<new-element xmlns="">new element text</new-element>
</content>
</body>
</root>
So how to stop the empty namespace being added in the newElement?
You need to assign the correct namespace to the new Element; in this case the same namespace as the parent element:
Element newElement = DocumentHelper.createElement(QName.get("new-element", element.getNamespace()));

Set multiple namespace with different prefix using jdom

I would like to have this format in xml
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:001.003.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:tech:xsd:pain.001.001.03">
<staff id="1">
<firstname>yong</firstname>
</staff>
</Document>
I am using the following code.
Namespace namespace = Namespace.getNamespace("urn:001.003.03");
Namespace namespace1 = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
Namespace namespace2 = Namespace.getNamespace("schemaLocation", "urn:tech:xsd:pain.001.001.03");
Element document = new Element("Document", namespace);
Document doc = new Document(document);
doc.setRootElement(document);
document.addNamespaceDeclaration(namespace1);
document.addNamespaceDeclaration(namespace2);
Element staff = new Element("staff", namespace);
staff.setAttribute(new Attribute("id", "1"));
staff.addContent(new Element("firstname",namespace).setText("yong"));
doc.getRootElement().addContent(staff);
I am getting output is:
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:001.003.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:schemaLocation="urn:tech:xsd:pain.001.001.03">
<staff id="1">
<firstname>yong</firstname>
</staff>
</Document>
I need namespace like xsi:schemaLocation but its generating namespace like xmlns:schemaLocation

Removing xml tags by using java

I have a very simple xml file that I would like to create a simple function to remove a tag from it. Here is my sample xml file:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channels>
<channel>
<items>
<item>
<title>Java Tutorials></title>
<link>http://www.tutorial-point.com/</link>
</item>
<item>
<title>Java Tutorials></title>
<link>http://www.javatpoint.com/</link>
</item>
</items>
</channel>
</channels>
</rss>
In my Java program, simply want to call a method to delete two tags from the file. I'm not very familiar with XML but did manage to create a reader and writer but now I'm having trouble creating a method to delete an item from my file.
// retrieve the element
Element element = (Element) doc.getElementsByTagName("channels").item(0);
Element element2 = (Element) doc.getElementsByTagName("channel").item(0);
// remove the specific node
element.getParentNode().removeChild(element);
element2.getParentNode().removeChild(element2);
When I used the above code in Java, it removed all the tags but I expected the result like below:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<items>
<item>
<title>Java Tutorials></title>
<link>http://www.tutorial-point.com/</link>
</item>
<item>
<title>Java Tutorials></title>
<link>http://www.javatpoint.com/</link>
</item>
</items>
</rss>
Can you please suggest?
Try this.
Element rss = (Element) doc.getElementsByTagName("rss").item(0);
Element channels = (Element) doc.getElementsByTagName("channels").item(0);
Element items = (Element) doc.getElementsByTagName("items").item(0);
rss.appendChild(items);
rss.removeChild(channels);

String to XML, The markup in the document following the root element must be well-formed

I know same sort of questions have already been answered but mine is bit different in nature, so i am trying to parse an XML-String to write it back to an already created xml file, the error i am getting is that
The markup in the document following the root element must be
well-formed.
Actually i know the error and the thing causing is that i don't have any root element in my generated-xml-string because i already have my root element in the xml i am just trying to append new xml tags to an already created file.
my xml file is:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<perk-users>
<user pin="73000001">
<property email="example#example.com"/>
<property username="73000001abcdef"/>
<property ecoid="AXHN6yllzrxGmJduzLzsiOk%3D"/>
</user>
<user pin="73000002">
<property email="example#example.com"/>
<property username="73000002abcdef"/>
<property ecoid="AXHN6yllzrxGmJduzLzsiOk%3D"/>
</user>
</perk-users>
And the xml string i have is:
<user id="73000009">
<property email="example#example.com"/>
<property username="73000009abcdef"/>
<property ecoid="AXHN6yllzrxGmJduzLzsiOk%3D"/>
</user>
<user id="73000004">
<property email="example#example.com"/>
<property username="73000004abcdef"/>
<property ecoid="AXHN6yllzrxGmJduzLzsiOk%3D"/>
</user>
The code is:
DocumentBuilderFactory dbFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = loadDocument();
Element rootElement = doc.getDocumentElement();
Document doc2 = dBuilder.parse(new ByteArrayInputStream(generatedXML.getBytes()));
Node node = doc.importNode(doc2.getDocumentElement(), true);
rootElement.appendChild(node);
writeToXML(doc);
So it basically crashes at dbuilder.parse() as i know there is no root element in my generatedXML, so please suggest me a way where i could write/append to <perk-users> this same xml string.

Java XSL Transformation complaining about binding prefix to namespace

I try to transform a XML-document which is a TCX-file from a Garmin Watch with XSL and the javax.xml.transform.Transformer. This is the document (shorten):
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2">
<Activities>
<Activity Sport="Running">
<Id>2014-08-23T15:36:15.000Z</Id>
<Lap StartTime="2014-08-23T11:50:34.000Z">
<TotalTimeSeconds>3181.0</TotalTimeSeconds>
<DistanceMeters>7620.0</DistanceMeters>
<MaximumSpeed>21.887998580932617</MaximumSpeed>
<Calories>386</Calories>
<AverageHeartRateBpm>
<Value>119</Value>
</AverageHeartRateBpm>
<MaximumHeartRateBpm>
<Value>167</Value>
</MaximumHeartRateBpm>
<Intensity>Active</Intensity>
<TriggerMethod>Manual</TriggerMethod>
<Track>
<Trackpoint>
<Time>2014-08-23T11:50:34.375Z</Time>
<Position>
<LatitudeDegrees>48.17259333333333</LatitudeDegrees>
<LongitudeDegrees>10.191565</LongitudeDegrees>
</Position>
<AltitudeMeters>542.5505981445312</AltitudeMeters>
<DistanceMeters>0.0</DistanceMeters>
<HeartRateBpm>
<Value>70</Value>
</HeartRateBpm>
<SensorState>Absent</SensorState>
</Trackpoint>
[...]
</Track>
<Notes>Note</Notes>
</Lap>
<Notes>Note</Notes>
<Training VirtualPartner="false">
<Plan Type="Workout" IntervalWorkout="false">
<Name>Running</Name>
<Extensions/>
</Plan>
</Training>
<Creator xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Device_t">
<Name>Polar V800</Name>
<UnitId>0</UnitId>
<ProductID>13</ProductID>
</Creator>
</Activity>
</Activities>
<Author xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Application_t">
<Name>no application</Name>
</Author>
</TrainingCenterDatabase>
I use the javax.xml.transform.Transformer for this task and get a strange error. The transformer gives me the following error message:
Element "xmlns:xsi" cannot have "xmlns" as its prefix.
It belongs to the line:
<Creator xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Device_t">
From my point of view, this line is valid. The given namespace is just bound to the prefix xsi. Is it necessary to configure the Transformer to detect it right or do I need to specify something in the xsl-file?
Thanks

Categories