请问如何在Java中创建像这样的xml标题。
<cfg:configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xmlns:ContentRouter="http://company/ContentRouter-3.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:cfg="http://company/configuration">.
我正在使用DocumentBuilderFactory
,我的xml看起来很相似,但它有点不同......
我的代码:
Element rootElement = doc.createElement("cfg:configuration");
Attr attr1 = doc.createAttribute("xmlns:xsi");
attr1.setValue("http://www.w3.org/2001/XMLSchema-instance");
Attr attr2 = doc.createAttribute("xmlns:ContentRoute");
attr2.setValue("http://eurotel/ContentRouter-3.0");
Attr attr3 = doc.createAttribute("xmlns:xs");
attr3.setValue("http://www.w3.org/2001/XMLSchema");
Attr attr4 = doc.createAttribute("xmlns:cfg");
attr4.setValue("http://eurotel/configuration");
感谢您的帮助!
答案 0 :(得分:0)
您可以按照以下方式执行此操作
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
public class RegexTest {
private static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
public static void main(String[] args) throws Exception {
RegexTest domTest = new RegexTest();
domTest.testXmlDocumentWithNamespaces();
}
public void testXmlDocumentWithNamespaces() throws Exception {
DocumentBuilder db = dbf.newDocumentBuilder();
DOMImplementation domImpl = db.getDOMImplementation();
Document document = addNameSpaces(domImpl);
serialize(domImpl, document);
}
private Document addNameSpaces(DOMImplementation domImpl) {
Document document = domImpl.createDocument("http://company/configuration", "cfg:configuration", null);
document.getDocumentElement().setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ContentRouter", "http://company/ContentRouter-3.0");
document.getDocumentElement().setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xs", "http://www.w3.org/2001/XMLSchema");
document.getDocumentElement().setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
return document;
}
private void serialize(DOMImplementation domImpl, Document document) {
DOMImplementationLS ls = (DOMImplementationLS) domImpl;
LSSerializer lss = ls.createLSSerializer();
LSOutput lso = ls.createLSOutput();
lso.setByteStream(System.out);
lss.write(document, lso);
}
}
打印:
<?xml version="1.0" encoding="UTF-8"?>
<cfg:configuration xmlns:cfg="http://company/configuration" xmlns:ContentRouter="http://company/ContentRouter-3.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>