2011-01-29 4 views
0

에 문자열로 XML 노드 내부의 내용을받을 수 있나요 :어떻게 내가 이런 식으로 뭔가를 찾고 있어요 자바

<Node1> 
    <Child2 attr1="abc"> 
    <Child3 attr2="xyz"> 
<Node1> 

는 노드 1에서, 나는 텍스트로 노드 내부의 내용을 싶어. 내가 원하는 출력

"<Child2 attr1="abc"><Child3 attr2="xyz">" 
+0

DOM을 사용하고 있습니다. – Anon

+0

XML 형식이 올바르지 않습니다. 웹에서 java xml 파서를 검색해 보셨습니까? –

+0

Google xpath를 참조하십시오. mistype.my XML을이었다 – CoolBeans

답변

1
//Parse the input document 
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder = factory.newDocumentBuilder(); 
     Document doc = builder.parse(new File("yourfile.xml")); 

     //Set up the transformer to write the output string 
     TransformerFactory tFactory = TransformerFactory.newInstance(); 
     Transformer transformer = tFactory.newTransformer(); 
     transformer.setOutputProperty("indent", "yes"); 
     StringWriter sw = new StringWriter(); 
     StreamResult result = new StreamResult(sw); 

     //Find the first child node 
     NodeList nl = doc.getDocumentElement().getChildNodes(); 
     DOMSource source = null; 
     for(int x = 0;x < nl.getLength();x++) 
     { 
      Node e = nl.item(x); 
      if(e instanceof Element) 
      { 
       source = new DOMSource(e); 
       break; 
      } 
     } 

     transformer.transform(source, result); 
     System.out.println(sw.toString()); 
    } 
} 

이 다른 가능한 답변이 question를 참조한다.

관련 문제