2014-12-16 3 views
1

xpath를 기반으로합니다. xml의 일부를 선택하고 일부를 선택하려면 다른 xml 소스로 사용하고 싶습니다.자바에서 xpath를 사용하여 XML의 일부를 얻는 방법

예 :

<root> 
    <a type="t1"> 
     <property name="data" value="val1"/> 
    </a> 
    <a type="t2"> 
     <property name="data" value="val2"/> 
    </a> 
    <a type="t1"> 
     <property name="data" value="val2"/> 
    </a> 
</root> 

의 XPath :/루트/A [@ 타입 = "T1"]/

선택된 XML은

<root> 
    <a type="t1"> 
     <property name="data" value="val1"/> 
    </a> 
    <a type="t1"> 
     <property name="data" value="val2"/> 
    </a> 
</root> 

동일 난으로 사용할 것 java에있는 다른 xml 소스. 도와주세요.

+0

XPath를 당신에게'NodeList'을 얻을 수있는 적절한 XPath 식을 전달하여 문자열로 XML 블록을 추출하는 데 사용할 수 있습니다, 당신은 두 번째를 구축하기 위해'NodeList'를 사용할 수' 문서 ' – MadProgrammer

+0

http://stackoverflow.com/questions/23933442/selenium-automation-finding-best-xpath/23934039#23934039 또는 브라우저에서 xml을 열고 U가 원하는대로 xpath를 얻을 때까지 요소를 선택하기 만하면됩니다. – SkorpEN

답변

1

로드 XML과 당신이 ...

DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); 
DocumentBuilder b = f.newDocumentBuilder(); 
Document d = b.parse(...); 

// Find all nodes with the attribute of type equal to `t1` 
// You could use //*/a[@type='t1'] if you wanted to narrow it down 
// This find ALL matches through out the document... 
String expression = "//*[@type='t1']"; 
XPath xPath = XPathFactory.newInstance().newXPath(); 
Object result = xPath.compile(expression).evaluate(d, XPathConstants.NODESET); 

NodeList nodes = (NodeList) result; 

찾고있는 노드를 찾아 새로운 Document 만들기 ....

Document d2 = b.newDocument(); 
Element root = d2.createElement("root"); 
d2.appendChild(root); 

두 번째로 처음부터 노드를 추가합니다. .. 초래한다

for (int i = 0; i < nodes.getLength(); i++) { 
    Node node = nodes.item(i); 
    d2.adoptNode(node); 
    root.appendChild(node); 
} 

...

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<root> 
    <a type="t1"> 
     <property name="data" value="val1"/> 
    </a> 
    <a type="t1"> 
     <property name="data" value="val2"/> 
    </a> 
</root> 
+0

부모 태그 이름을 얻을 수있는 방법이있어서 대상 문서에 넣을 수 있습니까? 내 경우에는 b'cos xml 소스 형식이 미리 정의되지 않았습니다. 고마워 :) – Jitendra

+0

그래,하지만 네가 그것을 원할 때 달렸어. 예를 들어'Node # getParent'를 사용하거나 실제로 xpath를 얻을 수있다. – MadProgrammer

0

에 따라 기능이

private static String nodeToString(Node node) throws TransformerException 
{ 
    StringWriter buf = new StringWriter(); 
    Transformer xform = TransformerFactory.newInstance().newTransformer(); 
    xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 
    xform.transform(new DOMSource(node), new StreamResult(buf)); 
    return(buf.toString()); 
} 

    public static void main(String[] args) throws Exception 
{ 
     DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
     Document doc = dBuilder.parse(inputFile); 

     XPath xPath = XPathFactory.newInstance().newXPath(); 
     Node result = (Node)xPath.evaluate("A/B/C", doc, XPathConstants.NODE); //"A/B[id = '1']" //"//*[@type='t1']" 

     System.out.println(nodeToString(result)); 

} 
관련 문제