2011-12-11 50 views
0

我正在使用Window Phone應用程序,我需要使用xpath和linq。不幸的是xpath目前不支持。我有一個xml文件,我遞歸鑽取作爲用戶選擇節點。 node()/ @標題被加載到一個列表框中。用戶選擇等。我通常會動態地構建xpath謂詞。在windows phone上使用linq-to-xml動態構建謂詞

例如:

<cfr> 
<chapter title="CHAPTER VI" volume="6"> 
    <subchapter title="SUBCHAPTER A" volume="6"> 
     <part number="600" title="PART 600"> 
      <subpart number="Subpart A" part="PART 600" title="Subpart A Farm Credit Administration"> 
       <section number="600.1" title="The Farm Credit Act." part="PART 600" link="12CFR600.1" type="cfr"/> 
       <section number="600.2" title="Farm Credit Administration." part="PART 600" link="12CFR600.2" type="cfr"/> 
      </subpart> 
     </part> 
     <part number="601" title="PART 601"> 
      <section number="601.1" title="The Credit Act." part="PART 601" link="12CFR6001.1" type="cfr"/> 
     </part> 
    </subchapter> 
    <part>......</part> 
</chapter> 
</cfr> 

在XPath我會用:

/node()/node()/node()/node()[@title='PART 601']/node()[@title='The Music Act.']/@title 

我跟蹤有多深的用戶點擊和指標。我想打造的XPath謂詞像這樣在C#:

private String XpathBuilder(bool isParentNode) 
    { 
     int nCount = AcmSinglton.NodeCount; 
     StringBuilder nodeStr = new StringBuilder(); 
     nodeStr.Append("/node()/node()"); 

     for (int i = 0; i < nCount; i++) 
     { 
      if (i != 0) 
      { 
       nodeStr.Append("[@title = '" + AcmSinglton.TitlePredicatesArrayList.get(i - 1).toString() + "']/node()"); 
      } 
      else 
      { 
       nodeStr.Append("/node()"); 
      } 
     } 
     return nodeStr.ToString(); 
    } 

所以我要尋找的想法,以動態地建立使用LINQ到XML的謂詞。

這是我到目前爲止有:

XDocument xml = XDocument.Load(String.Format("Resourses/c{0}x{1}.xml", this.CFRTitle, this.Volume));    
      var nodes = from x in xml.Elements().ElementAt(nodeDepth).Elements() 
         select new Menus.Chapter 
         { 
          Title = x.Attribute("title").Value 
         }; 

      this.MainListBox.ItemsSource = nodes.ToList(); 

回答

1

像這樣的東西應該工作:

var currentLevelElements = doc.Root.Elements(); 
int depth = 0; 
while (currentLevelElements != null && depth < nodeDepth) 
{ 
    currentLevelElements = currentLevelElements.Elements() 
               .Where(x=> (string) x.Attribute("title") == AcmSinglton.GetTitle(depth)); 
    depth++; 
} 
var nodes = from x in currentLevelElements select new Menus.Chapter 
        { 
         Title = x.Attribute("title").Value 
        }; 

似乎尷尬查詢辛格爾頓爲標題信息 - 這是一個依賴應直接傳入你的方法。