I dont have the xsd file of an xml document, so I must change to default xmlns "http://www.w3.org/2001/XMLSchema-instance" to pars the XML elements but there is a problem to do it, when I change xmlns attribute of root element (myroot) another attribute (xmlns) is created in the child element (data) with the value "myxsd.xsd". I want to ignore or change the value of xmlns ( myxsd.xsd ) to parse the document correctly.
My XML Input:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<myroot xmlns="myxsd.xsd" class="15">
<data att1="all" att2="actual">
<myobject patt1="patt1_value" patt2="patt2_value" patt3="patt3_value">
<p name="p1">page1</p>
<p name="p2">page1</p>
<p name="p3">page1</p>
<p name="p4">page4</p>
</myobject>
</data>
</myroot>
My XML Output:
<?xml version="1.0" encoding="UTF-8"?>
<myroot xmlns="http://www.w3.org/2001/XMLSchema-instance" class="15">
<data xmlns="myxsd.xsd" att1="all" att2="actual">
<myobject patt1="patt1_value" patt2="patt2_value" patt3="patt3_value">
<p name="p1">page1</p>
<p name="p2">page1</p>
<p name="p3">page1</p>
<p name="p4">page4</p>
</myobject>
</data>
</myroot>
My Code:
public void Edit_file() throws JDOMException, IOException {
InputStream in = new FileInputStream("C:\\small_test.xml");
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(in);
// getting the root element
Element root = document.getRootElement();
Namespace tempNamespace = Namespace.getNamespace("http://www.w3.org/2001/XMLSchema-instance");
root.setNamespace(tempNamespace);
// iterating over the children
List<Element> data = root.getChildren("data");
for (Element element : data) {
Attribute id = element.getAttribute("att1");
id.setValue("New value");
}
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(document, System.out);
}
I don't really understand why you want to move the elements into a different namespace (especially into the namespace http://www.w3.org/2001/XMLSchema-instance
, which is not intended for this purpose), but if you want to do it, you must change all the elements, not just the outermost one. Although the namespace declaration is only present on the outermost element, it has the effect of putting all the elements in this namespace, and they will remain in that namespace unless you change them.