在 C# 中读取 XML - 抓取特定元素

Reading in XML in C# - Grab specific Element

我正在阅读一些 XML 并将其显示在效果很好的 DataGridView 中。

但是,如果我可以抓取特定元素并阅读其内容,我的生活会轻松 10 倍。 (我正在使用 XmlReader)

另外,有没有简单的循环遍历元素的方法?我需要获取计数然后遍历每个 "Facility" 但我似乎无法正常工作。添加另一个 "While(read)" 并不是一个很好的解决方案。

我现在不想切换到另一个 reader,我现在正在深入研究这个。

XML数据:

    <data>
    <count>2</count>
    <facility>
        <typeId>1</typeId>
        <type>Beds</type>
        <quantity>0</quantity>
        <description>null</description>
    </facility>
    <facility>
        <typeId>2</typeId>
        <type>EDBeds</type>
        <quantity>0</quantity>
        <description>null</description>
    </facility>
</data>

代码:

while (xr.Read())
{
    if (xr.Name.Equals("count"))
    {
        valueName.Text = "We currently have " + xr.ReadElementContentAsString() + " facilities open.";
    }
    while (xr.ReadToFollowing("facility"))
    {
        //Add a new row for data if we are at a new Facility element
        if (xr.NodeType == XmlNodeType.Element && xr.Name == "facility")
        {
            row = generalData.Rows.Add();
            col = 0;
        }
        //Loop through current facility Element
    }
}

抢先一步,使用 "ReadSubTree()" 效果很好:

                    XmlReader inner = xr.ReadSubtree();
                    while (inner.Read())
                    {
                        if (xr.NodeType == XmlNodeType.Text)
                        {
                             //Do stuff
                        }
                    }

看看这个 post 为什么你应该更喜欢 XDocument 而不是 XmlReader。正如它所述,XDocument 的 API 更容易并且支持 'LINQ To XML'。 XmlReader 已过时,因为它已过时且包含错误。

var xml = @"
<data>
    <count>2</count>
    <facility>
        <typeId>1</typeId>
        <type>Beds</type>
        <quantity>0</quantity>
        <description>null</description>
    </facility>
    <facility>
        <typeId>2</typeId>
        <type>EDBeds</type>
        <quantity>0</quantity>
        <description>null</description>
    </facility>
</data>";

var xDocument = XDocument.Load( new StringReader( xml ) );
var facilityElements = xDocument.Descendants().Where( x => x.Name == "facility" );

// Count the elements
var count = facilityElements.Count();

foreach ( var facilityElement in facilityElements )
{
    // Handle elements
}

// Adds an facility element
var facility = new XElement( "facility" );
var typeId = new XElement( "typeId" );
typeId.SetValue(3);
facility.Add( typeId );
xDocument.Element( "data" ).Add( facility );

对于给定的 XML 数据,我们不需要遍历每个 'facility' 元素来将它的数据绑定到 DataGridView 上。

相反,我们可以按照以下简单步骤操作,

DataSet ds = new DataSet();
ds.ReadXml(xr);
dataGridView1.DataSource = ds.Tables["facility"];

--SJ