2014-03-03 2 views
1

많은 링크가 있다는 것을 알고 있지만 해결책을 찾을 수 없습니다. 내가 "필드 이름 = 'ID'의 값을 취득 할XML이 특정 속성에서 노드의 값을 얻습니다.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<Entity Type="test-folder"> 
<Fields> 
<Field Name="item-version"/> 
<Field Name="id"> 
    <Value>5386</Value> 
</Field> 
<Field Name="ver-stamp"> 
    <Value>2</Value> 
</Field> 
<Field Name="parent-id"> 
    <Value>5310</Value> 
</Field> 
<Field Name="system"> 
    <Value>A</Value> 
</Field> 
<Field Name="last-modified"> 
    <Value>2014-03-03 16:35:24</Value> 
</Field> 
<Field Name="description"> 
    <Value/> 
</Field> 
<Field Name="hierarchical-path"> 
    <Value>AAAAAPAADAACADC</Value> 
</Field> 
<Field Name="view-order"> 
    <Value>0</Value> 
</Field> 
<Field Name="name"> 
    <Value>TC77</Value> 
</Field> 
<Field Name="attachment"> 
    <Value/> 
</Field> 
</Fields> 

: 이것은 내 XML 파일입니다

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder = factory.newDocumentBuilder(); 
InputSource is = new InputSource(); 
is.setCharacterStream(new StringReader(xml)); 

Document doc = builder.parse(is); 
XPathFactory xPathfactory = XPathFactory.newInstance(); 
XPath xpath = xPathfactory.newXPath(); 

XPathExpression expr = xpath.compile("//Field[@Name=\"id\"]"); 
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); 
System.out.println(nl.getLength()); 
for(int i=0;i<nl.getLength();i++){ 
    Node currentItem = nl.item(i); 
    String key = currentItem.getAttributes().getNamedItem("Name").getNodeValue(); 
    System.out.println(key); 
} 

: 내 검색을 바탕으로 좀 코드로 올라와있다 "5386입니다. 죄송합니다. 방금 다시 게시하는 중이라면 정말 답을 얻을 수 없었습니다.

답변

1

코드에서 이름 속성이 "Id"인 필드 노드가 나타납니다. name 속성이 "Id"인 요소의 Value 노드에서 요소 텍스트를 가져 오도록 XPath 표현식을 변경할 수 있습니다. 그래서 XPath 표현식은 다음과 같아야합니다

//Field[@Name=\"id\"]/Value/text() 

그런 다음 올바른 가치 요소를 찾을 수

 Node currentItem = nl.item(i); 
     System.out.println(currentItem.getNodeValue()); 
+0

이 방법을 사용하면 여러 텍스트 노드를 직접 연결해야합니다. 일반적으로'string (...) '함수를 사용하여 XPath 엔진이이를 수행하도록하는 것이 더 간단합니다. – Karsten

1

이 XPath에에 대한 루프의 코드를 변경합니다 //Field[@Name="id"]/Value

을 또한 XPath를 얻을 수 있습니다 표현식 string(//Field[@Name="id"]/Value)을 통해 요소의 연결된 텍스트 내용을 반환하려면이 방법이 가장 간단 할 것입니다. 이 경우 노드 목록이 아닌 expr.evaluate에서 직접 문자열을 가져와야합니다.

관련 문제