简体   繁体   English

如何根据兄弟节点的值获取 XML 节点?

[英]How to fetch XML node based on value of sibling node?

I'm working on a .Net application for which I need to fetch values from a XML file based on the value of its sibling node's value.Eg: Here in the XML I want to fetch the values in Pages, Price & Author based on the title "Hansel and Gretel".我正在开发一个 .Net 应用程序,我需要根据其兄弟节点的值从 XML 文件中获取值。例如:在 XML 中,我想获取基于页面、价格和作者的值标题“汉塞尔和格莱特”。

<?xml version="1.0" encoding="utf-8"?>
<Books>
  <Book>
    <Title>Hansel and Gretel</Title>
    <Pages>221</Pages>
    <Price>3.5</Price>
    <Author>Grimm</Author>
  </Book>
  <Book>
    <Title>Green Eggs and Ham</Title>
    <Pages>145</Pages>
    <Price>5.25</Price>
    <Author>Dr. Seuss</Author>
  </Book>
</Books>

Rather than searching for siblings, you can search for all parent elements <Book> with a conditional clause filtering for those with a certain value for their <Title> child element.您可以搜索所有父元素<Book> ,而不是搜索兄弟元素,并使用条件子句过滤那些具有特定值的<Title>子元素。 Then, for all matches, return the values of the three desired child elements.然后,对于所有匹配项,返回三个所需子元素的值。

This can most easily be done using LINQ to XML :使用LINQ to XML最容易做到这一点:

var root = XElement.Parse(xmlString);

var title = "Hansel and Gretel";

var query = root
    .Elements("Book")
    .Where(e => (string)e.Element("Title") == title)
    .Select(e => new 
            {
                Pages = (int)e.Element("Pages"),
                Price = (decimal)e.Element("Price"),
                Author = (string)e.Element("Author"),
            });

var results = query.ToList();

However, if you prefer using XPath queries, you could do:但是,如果您更喜欢使用XPath查询,则可以执行以下操作:

var query = root
    .XPathSelectElements(string.Format("/Book[Title='{0}']", title))
    .Select(e => new 
            {
                Pages = (int)e.Element("Pages"),
                Price = (decimal)e.Element("Price"),
                Author = (string)e.Element("Author"),
            });

Demo fiddle here .演示小提琴在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM