예를 들어 네임 스페이스를 사용하는 XML 문서를 구성 할 수있는 Java 코드를 찾고 있습니다. 내 평범한 것을 사용하는 것을 찾을 수없는 것 같습니다 favourite tool 그래서 누군가가 나를 도울 수 있기를 바랬습니다.Java에서 네임 스페이스를 사용하여 XML 문서 만들기
18
A
답변
14
나는 당신이 무엇을 하려는지 확실하지 않지만, 대부분의 xml-issues에는 jdom을 사용하고 네임 스페이스를 지원합니다 (물론).
코드 :
Document doc = new Document();
Namespace sNS = Namespace.getNamespace("someNS", "someNamespace");
Element element = new Element("SomeElement", sNS);
element.setAttribute("someKey", "someValue", Namespace.getNamespace("someONS", "someOtherNamespace"));
Element element2 = new Element("SomeElement", Namespace.getNamespace("someNS", "someNamespace"));
element2.setAttribute("someKey", "someValue", sNS);
element.addContent(element2);
doc.addContent(element);
은 다음 XML을 생성합니다
<?xml version="1.0" encoding="UTF-8"?>
<someNS:SomeElement xmlns:someNS="someNamespace" xmlns:someONS="someOtherNamespace" someONS:someKey="someValue">
<someNS:SomeElement someNS:someKey="someValue" />
</someNS:SomeElement>
당신이 필요로하는 모든 것을 포함해야합니다. 희망이 도움이됩니다.
20
이렇게하는 방법에는 여러 가지가 있습니다. 예 그냥 몇 :
W3C DOM
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
public class DomTest {
private static DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
public static void main(String[] args) throws Exception {
DomTest domTest = new DomTest();
domTest.testXmlDocumentWithNamespaces();
}
public void testXmlDocumentWithNamespaces() throws Exception {
DocumentBuilder db = dbf.newDocumentBuilder();
DOMImplementation domImpl = db.getDOMImplementation();
Document document = buildExampleDocumentWithNamespaces(domImpl);
serialize(domImpl, document);
}
private Document buildExampleDocumentWithNamespaces(
DOMImplementation domImpl) {
Document document = domImpl.createDocument("urn:example.namespace",
"my:example", null);
Element element = document.createElementNS("http://another.namespace",
"element");
document.getDocumentElement().appendChild(element);
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);
}
}
의 자바 구현을 사용하여 그리고 당신은 접두사와 요소 이름을 원하는 경우 (XOM을 사용), 단순히 새로운 요소 ("접두어를 호출 XOM
사용 : element ","urn : example.namespace "); –