Java에서 문자열 XML 조각을 문서 노드로 변환
Java에서 XML 문서에 삽입하기 위해 XML 조각을 나타내는 문자열을 어떻게 변환 할 수 있습니까?
예 :
String newNode = "<node>value</node>"; // Convert this to XML
그런 다음이 노드를 주어진 노드의 자식으로 org.w3c.dom.Document에 삽입 하시겠습니까?
Element node = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(new ByteArrayInputStream("<node>value</node>".getBytes()))
.getDocumentElement();
문서의 가져 오기 (또는 채택 ) 메소드를 사용하여 XML 조각을 추가 할 수 있습니다.
/**
* @param docBuilder
* the parser
* @param parent
* node to add fragment to
* @param fragment
* a well formed XML fragment
*/
public static void appendXmlFragment(
DocumentBuilder docBuilder, Node parent,
String fragment) throws IOException, SAXException {
Document doc = parent.getOwnerDocument();
Node fragmentNode = docBuilder.parse(
new InputSource(new StringReader(fragment)))
.getDocumentElement();
fragmentNode = doc.importNode(fragmentNode, true);
parent.appendChild(fragmentNode);
}
그만한 가치가있는 것은 dom4j 라이브러리 를 사용하여 생각 해낸 솔루션 입니다. (나는 그것이 작동하는지 확인했다.)
XML 조각을 a로 읽어옵니다 org.dom4j.Document
(참고 : 아래에 사용 된 모든 XML 클래스는 org.dom4j에서 가져온 것입니다. 부록 참조).
String newNode = "<node>value</node>"; // Convert this to XML
SAXReader reader = new SAXReader();
Document newNodeDocument = reader.read(new StringReader(newNode));
그런 다음 새 노드가 삽입 된 문서와 여기에서 부모 요소 (될)를 가져옵니다. (여기에서 org.w3c.dom.Document를 org.dom4j.Document로 변환해야합니다.) 테스트 목적으로 다음과 같이 만들었습니다.
Document originalDoc =
new SAXReader().read(new StringReader("<root><given></given></root>"));
Element givenNode = originalDoc.getRootElement().element("given");
새 자식 요소를 추가하는 것은 매우 간단합니다.
givenNode.add(newNodeDocument.getRootElement());
끝난. originalDoc
이제 출력 하면 다음이 생성됩니다.
<?xml version="1.0" encoding="utf-8"?>
<root>
<given>
<node>value</node>
</given>
</root>
부록 : 귀하의 질문에 회담이 약하므로 org.w3c.dom.Document
, 여기에 사이에 변환하는 방법입니다 org.dom4j.Document
.
// dom4j -> w3c
DOMWriter writer = new DOMWriter();
org.w3c.dom.Document w3cDoc = writer.write(dom4jDoc);
// w3c -> dom4j
DOMReader reader = new DOMReader();
Document dom4jDoc = reader.read(w3cDoc);
(두 종류의 Document
s가 정기적으로 필요하면 깔끔한 유틸리티 메서드에 넣는 것이 합리적 일 수 있습니다. 아마도 호출 된 클래스 XMLUtils
나 이와 비슷한 것입니다.)
타사 라이브러리 없이도이를 수행하는 더 좋은 방법이있을 수 있습니다. 그러나 지금까지 제시된 솔루션 중에서 dom4j <-> w3c 변환을 수행해야하는 경우에도 이것이 가장 쉬운 방법이라고 생각합니다.
업데이트 (2011) : 코드에 dom4j 종속성을 추가하기 전에 적극적으로 유지 관리되는 프로젝트 가 아니며 다른 문제도 있습니다 . 개선 된 버전 2.0은 오랫동안 작업 해 왔지만 알파 버전 만 사용할 수 있습니다. 대신 XOM과 같은 대안을 고려할 수 있습니다. 위에 링크 된 질문에서 더 많은 것을 읽으십시오.
여기 내 dom4j 답변 과 경쟁 하는 XOM 라이브러리를 사용하는 또 다른 솔루션 이 있습니다 . (이것은 XOM이 하나의 옵션으로 제안 된 좋은 dom4j 대체품을 찾는 나의 탐구의 일부입니다 .)
먼저 XML 조각을 다음으로 읽습니다 nu.xom.Document
.
String newNode = "<node>value</node>"; // Convert this to XML
Document newNodeDocument = new Builder().build(newNode, "");
그런 다음 조각이 추가 된 문서와 노드를 가져옵니다. 다시 테스트 목적으로 문자열에서 문서를 만듭니다.
Document originalDoc = new Builder().build("<root><given></given></root>", "");
Element givenNode = originalDoc.getRootElement().getFirstChildElement("given");
이제 자식 노드를 추가하는 것은 간단하고 dom4j와 비슷합니다 (XOM이 이미 속한 원래 루트 요소를 추가 할 수 없다는 점을 제외하면 newNodeDocument
).
givenNode.appendChild(newNodeDocument.getRootElement().copy());
문서를 출력하면 올바른 결과 XML이 생성됩니다 (XOM을 사용하면 매우 쉽습니다.에서 반환 한 문자열 만 인쇄하면됩니다 originalDoc.toXML()
).
<?xml version="1.0"?>
<root><given><node>value</node></given></root>
(만들기 및 줄 바꿈을 사용하여 XML 형식을 멋지게 지정하려면 Serializer
;을 사용하십시오 . Peter Štibraný에게 감사드립니다.)
So, admittedly this isn't very different from the dom4j solution. :) However, XOM may be a little nicer to work with, because the API is better documented, and because of its design philosophy that there's one canonical way for doing each thing.
Appendix: Again, here's how to convert between org.w3c.dom.Document
and nu.xom.Document
. Use the helper methods in XOM's DOMConverter
class:
// w3c -> xom
Document xomDoc = DOMConverter.convert(w3cDoc);
// xom -> w3c
org.w3c.dom.Document w3cDoc = DOMConverter.convert(xomDoc, domImplementation);
// You can get a DOMImplementation instance e.g. from DOMImplementationRegistry
/**
*
* Convert a string to a Document Object
*
* @param xml The xml to convert
* @return A document Object
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static Document string2Document(String xml) throws IOException, SAXException, ParserConfigurationException {
if (xml == null)
return null;
return inputStream2Document(new ByteArrayInputStream(xml.getBytes()));
}
/**
* Convert an inputStream to a Document Object
* @param inputStream The inputstream to convert
* @return a Document Object
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static Document inputStream2Document(InputStream inputStream) throws IOException, SAXException, ParserConfigurationException {
DocumentBuilderFactory newInstance = DocumentBuilderFactory.newInstance();
newInstance.setNamespaceAware(true);
Document parse = newInstance.newDocumentBuilder().parse(inputStream);
return parse;
}
If you're using dom4j, you can just do:
Document document = DocumentHelper.parseText(text);
(dom4j now found here: https://github.com/dom4j/dom4j)
...and if you're using purely XOM, something like this:
String xml = "<fakeRoot>" + xml + "</fakeRoot>";
Document doc = new Builder( false ).build( xml, null );
Nodes children = doc.getRootElement().removeChildren();
for( int ix = 0; ix < children.size(); ix++ ) {
otherDocumentElement.appendChild( children.get( ix ) );
}
XOM uses fakeRoot internally to do pretty much the same, so it should be safe, if not exactly elegant.
Try jcabi-xml, with a one liner:
Node node = new XMLDocument("<node>value</node>").node();
참고URL : https://stackoverflow.com/questions/729621/convert-string-xml-fragment-to-document-node-in-java
'Program Club' 카테고리의 다른 글
Java에서 선언과 정의의 차이점은 무엇입니까? (0) | 2020.10.29 |
---|---|
프로젝트 오류 : QT의 알 수없는 모듈 : webkitwidgets (0) | 2020.10.29 |
MySQL : (제품) 가격에 선호되는 열 유형? (0) | 2020.10.29 |
SQL Server에서 날짜 만 사용하여 DATETIME 필드를 쿼리하는 방법은 무엇입니까? (0) | 2020.10.28 |
Visual Studio Code에서 터미널을 어떻게 지울 수 있습니까? (0) | 2020.10.28 |