<?xml version="1.0" encoding="utf-8" ?>
<PrimaryLink>
<LinkID>p1</LinkID>
<SecondaryLink>
<LinkID>s1</LinkID>
<LeftMenu>
<NavLinks>
<LinkID>n1</LinkID>
</NavLinks>
<NavLinks>
<LinkID>n2 </LinkID>
</NavLinks>
</LeftMenu>
</SecondaryLink>
</PrimaryLink>
C#
var menuItems1 = from c in xMenuElement.Elements("GlobalNavigation").Elements("PrimaryLink")
select c;
通过将n1作为输入
,我喜欢p1->s1->n1
的ans
答案 0 :(得分:0)
这是一个解决方案。它不是很漂亮,但它可以满足您的需求。
string xmlContent=@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<PrimaryLink>
<LinkID>p1</LinkID>
<SecondaryLink>
<LinkID>s1</LinkID>
<LeftMenu>
<NavLinks>
<LinkID>n1</LinkID>
</NavLinks>
<NavLinks>
<LinkID>n2</LinkID>
</NavLinks>
</LeftMenu>
</SecondaryLink>
</PrimaryLink>";
XDocument doc = XDocument.Parse(xmlContent);
var targetNode = doc.Descendants().Where(p=>p.Value=="n1").FirstOrDefault();
string path = null;
if (targetNode!=null)
{
path=targetNode.AncestorsAndSelf().Elements("LinkID").Select(p => p.Value).Aggregate((i, j) => j + "=>" + i);
}
它将显示“p1 =&gt; s1 =&gt; n1”