JDOM2,xmlns(xsd)可以更改或从XML文档中删除

我没有xml文档的xsd文件,所以我必须更改为默认的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” . 我想忽略或更改xmlns(myxsd.xsd)的值来正确解析文档 .

我的XML输入:

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

我的XML输出:

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

我的代码:

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

}

回答(1)

2 years ago

我真的不明白你为什么要将元素移动到不同的命名空间(尤其是命名空间 http://www.w3.org/2001/XMLSchema-instance ,这不是为了这个目的),但如果你想这样做,你必须改变所有的元素,而不仅仅是最外层的 . 尽管名称空间声明仅出现在最外层元素上,但它具有将所有元素放在此命名空间中的效果,除非您更改它们,否则它们将保留在该命名空间中 .