我正在尝试从Java生成XML。
这样的事情:
<?xml version="1.0" encoding="UTF-8"?>
<ElementFile
xmlns="http://www.url.com/bla/bla"
xmlns:common="http://www.url.com/bla/bla/bla">
<Regulation>
<blablaElement>0000-0000</blablaElement>
</Regulation>
</ElementFile>
为此,我编写了以下代码:
ElementFile = document.addElement( "ElementFile" )
.addNamespace("xmlns","http://www.url.com/bla/bla")
.addNamespace("common", "http://www.url.com/bla/bla/bla");
但生成的代码是:
<?xml version="1.0" encoding="UTF-8"?>
<ElementFile
xmlns:xmlns="http://www.url.com/bla/bla"
xmlns:common="http://www.url.com/bla/bla/bla">
<Regulation>
<blablaElement>0000-0000</blablaElement>
</Regulation>
</ElementFile>
但是,如果我写这个(没有xmlns)
ElementFile = document.addElement( "ElementFile" )
.addNamespace("","http://www.url.com/bla/bla")
.addNamespace("common", "http://www.url.com/bla/bla/bla");
然后,xml正确生成行,但默认添加xmlns =“”:
<?xml version="1.0" encoding="UTF-8"?>
<ElementFile
xmlns="http://www.url.com/bla/bla"
xmlns:common="http://www.url.com/bla/bla/bla">
<Regulation xmlns="">
<blablaElement>0000-0000</blablaElement>
</Regulation>
</ElementFile>
我很失落......
[更新的问题]
对不起,但我不明白如何在我的代码中整合你的答案。我是这个领域的新手。
我的完整代码是:
XMLWriter writer = new XMLWriter(new FileWriter("xmlFileName"), format);
Document document = DocumentHelper.createDocument();
Element ElementFile = document.addElement( "ElementFile" )
.addNamespace("xmlns","http://www.url.com/bla/bla")
.addNamespace("xmlns:common", "http://www.url.com/bla/bla/bla");
Element Regulation = ElementFile.addElement( "Regulation" );
Element blablaElement = Regulation.addElement( "blablaElement" )
.addText( "0000-0000" );
writer.write(document);
writer.close();
答案 0 :(得分:1)
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setNamespaceAware(true);
DocumentBuilder docBuilder;
docBuilder = dbfac.newDocumentBuilder();
DOMImplementation domImpl = docBuilder.getDOMImplementation();
Document doc = domImpl.createDocument("http://www.url.com/bla/bla", "ElementFile ", null);
doc.setXmlVersion("1.0");
doc.setXmlStandalone(true);
Element elementFile = doc.getDocumentElement();
elementFile.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:common","http://www.url.com/bla/bla/bla");
并向此文档添加元素
您在此处有类似的问题:How to create attribute (xmlns:xsd) to XML node in Java?