これを試して:
DocumentBuilderFactory documentBuildFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder doccumentBuilder = documentBuildFactory.newDocumentBuilder();
Document document =
doccumentBuilder.parse(new ByteArrayInputStream("<name>Oscar</name>".getBytes()));
次の方法でトラバースできますOscar
。
String nodeText = document.getChildNodes().item(0).getTextContent() ;
System.out.println(nodeText);
元に戻すには:
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
//to print the string in sysout, System.out
StreamResult streamResult = new StreamResult(System.out);
transformer.transform(domSource, streamResult );
結果を文字列で取得するには:
DOMSource source = new DOMSource(document);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
StreamResult result = new StreamResult(outStream);
transformer.transform(source, result);
String resultString = new String( outStream.toByteArray());
System.out.println(resultString);