Reputation: 550
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
?
Upvotes: 1
Views: 178
Reputation: 12817
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()));
Upvotes: 0