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

本文关键字:子节点 第一个 获取 父节点 何单独 | 更新日期: 2023-09-27 17:50:35

我有以下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#代码?

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

听起来您只需要将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");
}

使用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();
        }
    }
}​

您可以使用LINQ解析为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");