如何单独获取第一个父节点子节点名称值?

时间:2015-05-25 10:30:15

标签: c# xml-parsing linq-to-xml

我的文件结构低于xml。

<BookStore>
    <Book Id="1">
      <Subject>
        <Rank ID="Chemistry">
            <a>A</a>
        </Rank>
        <Rank ID="Physics">
            <b>B</b>
        </Rank>
      </Subject>
    </Book>
    <Book Id="2">
      <Subject>
        <Rank ID="Science">
            <a>C</a>
        </Rank>
        <Rank ID="English">
            <b>D</b>
        </Rank>
      </Subject>
    </Book>
</BookStore>

我想在迭代时单独获得化学和物理价值。我如何解析并单独获得该值。

我尝试过以下代码。所以我得到了4个值。

var platformNodeList1 = xmlSourceFile.SelectNodes("BookStore/Book/Subject/Rank");

任何人都可以就此提出宝贵的建议吗?

任何人都可以告诉我如何通过c#代码将....带入一个字符串?

3 个答案:

答案 0 :(得分:0)

您可以使用LINQ to XML进行解析,并使用LINQ找到所需的元素:

 var doc = XDocument.Parse(xml);

 var firstBook = doc.Descendants("Book")
     .Single(e => (string)e.Attribute("Id") == "1");

 var firstBookRanks = doc.Descendants("Book")
     .Where(e => (string)e.Attribute("Id") == "1")
     .Descendants("Rank");

 var chemistry = doc.Descendants("Rank")
     .Single(e => (string)e.Attribute("ID") == "Chemistry");

 var physics = doc.Descendants("Rank")
     .Single(e => (string)e.Attribute("ID") == "Physics");

答案 1 :(得分:0)

听起来你只需要将XPath查询调整为......

var platformNodeList1 = xmlSourceFile.SelectNodes("BookStore/Book[@Id='1']/Subject/Rank");

或者如果你想迭代书籍......

var books = xmlSourceFile.SelectNodes("BookStore/Book");

foreach(var book in books) {
    var ranks = book.SelectNodes("Subject/Rank");
}

答案 2 :(得分:0)

使用XML Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =
                "<BookStore>" +
                "<Book Id=\"1\">" +
                  "<Subject>" +
                    "<Rank ID=\"Chemistry\">" +
                        "<a>A</a>" +
                    "</Rank>" +
                    "<Rank ID=\"Physics\">" +
                        "<b>B</b>" +
                    "</Rank>" +
                  "</Subject>" +
                "</Book>" +
                "<Book Id=\"2\">" +
                  "<Subject>" +
                    "<Rank ID=\"Science\">" +
                        "<a>C</a>" +
                    "</Rank>" +
                    "<Rank ID=\"English\">" +
                        "<b>D</b>" +
                    "</Rank>" +
                  "</Subject>" +
                "</Book>" +
                "</BookStore>";

            XDocument xmlSourceFile = XDocument.Parse(input);

            var platformNodeList1 = xmlSourceFile.Descendants("Rank").Select(x => x.Attribute("ID").Value).ToList();
        }
    }
}​