2009-04-24 4 views
2

다음과 같이 XmlDocument Example.xml의 일부가 있습니다.XmlDocument의 NodeList에서 특성을 가져 오려면?

<rapaine dotoc="palin" domap="rattmin"> 
    <derif meet="local" /> 
    <derif meet="intro" /> 
. 
. 
. 
</rapaine> 

여기에서 Nodelist를 만들고 속성을 가져 오기 위해 raplin 요소를 가져옵니다.

이제 속성 'dotoc'과 'domap'이 항상 fixed 인 각각의 값을 갖는 rapaine의 속성인지 확인하고 싶습니다. 그런 다음 'meet'속성을 사용하여 childNodes 'deriff'에 액세스 할 수 있습니다. . 여기 값만 바뀝니다.
코드의 일부를 작성했지만 컴파일 오류는 없지만 디버깅 할 때 for 루프 내에서 속성 및 하위 노드를 검사하지 않는다는 것을 알았습니다.

XmlNodeList listOfSpineRootNodes = opfXmlDoc.GetElementsByTagName("rapine"); 
for (int x = 0; x < listOfSpineRootNodes.Count; x++) 
    { 
    XmlAttributeCollection spineAttributes = listOfSpineRootNodes[x].Attributes; 
    string id = spineAttributes[0].Value; 
    if (spineAttributes != null) 
    { 
     XmlNode attrToc = spineAttributes.GetNamedItem("dotoc"); 
     XmlNode attrPageMap = spineAttributes.GetNamedItem("domap"); 
     if (attrToc.Value == "palin" && attrPageMap.Value == "rattmine") 
     { 
     if (listOfSpineRootNodes != null) 
     { 
      foreach (XmlNode spineNodeRoot in listOfSpineRootNodes) 
      { 
      XmlNodeList listOfSpineItemNodes = spineNodeRoot.ChildNodes; 
      if (listOfSpineItemNodes != null) 
      { 
       foreach (XmlNode spineItemNode in listOfSpineItemNodes) 
       { 
       if (spineItemNode.NodeType == XmlNodeType.Element 
        && spineItemNode.Name == "derif") 
       { 
        XmlAttributeCollection spineItemAttributes = spineItemNode.Attributes; 

        if (spineItemAttributes != null) 
        { 
        XmlNode attrIdRef = spineItemAttributes.GetNamedItem("meet"); 
        if (attrIdRef != null) 
        { 
         spineListOfSmilFiles.Add(attrIdRef.Value); 
        } 
        } 
       } 
       } 
      } 
      } 
     } 
     } 
    } 

어디로 잘못 가고 있는지 말해 주시겠습니까 .. 고마워 ....

답변

2

XPath를 사용하여 다음 코드를 사용하여이 작업을 수행 할 수 있습니다. XPath는 XML 문서를 쿼리하기 위해 특별히 설계된 언어이기 때문에 XML 문서를 배워야합니다. 대부분의 초보자는 W3schools에서 학습을 시작하고 싶습니다. 참고로

XmlNodeList meetList = opfXmlDoc.SelectNodes("/rapaine[(@dotoc = 'palin') and (@domap = 'rattmin')]/derif/@meet") 
if (meetList.Count > 0) 
{ 
    foreach (XmlNode meet in meetList) 
    { 
    spineListOfSmilFiles.Add(meet.Value); 
    } 
} 

, XPath 식 :

/rapaine[(@dotoc = 'palin') and (@domap = 'rattmin')]/derif/@meet 

과 같이 설명 될 수있다 : 여기

코드입니다

a)에있는 모든 rapaine 루트 레벨 요소를 찾기 값이 "palin"인 속성 dotoc과 속성 값이 "rattmin"인 domap도 있습니다.

b) rapaine 요소 내에는 모두 derif 개의 하위 항목이 있습니다.

c) derif 개의 요소 내에 모두 meet 속성을 검색하십시오.

코드가 얼마나 간결하게 표시되는지 확인하십시오.

+0

오, 그 위대한 Luks. 링크 및 코드의 일부를 가져 주셔서 감사합니다. –

+0

내 기쁨! 행복한 학습. :-) – Cerebrus

0

당신은 단순한 XPath 식으로이 문제를 해결할 수 없습니다 .... 말해 주시겠습니까?

조건이있는 모든 중첩 루프는 단순히 문제를 묻는 것입니다.

+0

아니요. XPath를 사용할 수 없습니다. 정직하게는 여기 XPath를 사용하는 방법을 모릅니다. 감사합니다. –

+0

네, XPath를 사용할 수는 있지만 살펴 봐야 할 것입니다. – Natrium

+0

전체 문제가 하나의 표현식으로 해결 될 것이라고 말하는 것이 아니며, 작은 조각으로 나누고 싶을 수도 있습니다. 반복 작업이 필요할 수도 있지만, 일반적으로 가능하다고 확신합니다. –

0

사용하는 .NET의 버전에 따라 LINQ가이를 단순화 할 수 있습니다.

관련 문제