I am working on a Window Phone app were I need to use xpath with linq. Unfortunately xpath is not currently supported. I have an xml file that I recursively drill down as the user select nodes. The node()/@title is loaded into a listbox. The user selects and so-on. I normally would dynamically build the xpath predicates.
For example:
<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>
In xpath I would use:
/node()/node()/node()/node()[@title='PART 601']/node()[@title='The Music Act.']/@title
I keep track of how deep the user has clicked and which index. I would build the xpath predicate like so in 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();
}
So I am looking for idea to dynamically build predicates using linq-to-xml.
Here is what I have so far:
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();
Something like this should work:
It seems awkward to query a Singleton for the title information – this is a dependency that should be passed into your method directly.