使用属性从XML读取数据

时间:2014-10-08 10:38:17

标签: c# .net xml c#-4.0 xml-parsing

我有一个XML文件,如下所示:

<CPageDataXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<control id="busRowOAppr2EIDLookUpUserControl" controltype="business">
    <field controlvaluetype="single" key="busRowOAppr2EIDLookUpUserControl_txtEID">
      <valuefield value="709227">E8 - John Doe</valuefield>
    </field>
    <field controlvaluetype="hidden_single" key="busRowOAppr2EIDLookUpUserControl_txtEID_Email">
      <valuefield value="_JohnDoe@Wonder.com">emailid</valuefield>
    </field>
</control>
<control id="busDelegationFromDate123" controltype="business">
    <field controlvaluetype="single" key="txtCalanderDateWithImage_UserControl">
      <valuefield value="" />
    </field>
</control>
</CPageDataXML>

我想读取值字段的值,其中control id =&#34; busRowOAppr2EIDLookUpUserControl&#34;

C#代码是: 这是加载XML的代码:

XmlDocument xPagedata=new XmlDocument();
XmlNode xnodePagedata = null;
xPagedata.LoadXml(strPageData);

这是SelectSingleNode的代码:

string a = xnodePagedata.SelectSingleNode(//Control[@id='busRowOAppr2EIDLookUpUserControl']).Attributes["Value"].Value;

我试过使用SelectSingleNode(string)但是这给了我一个空引用异常。请建议我该如何处理这个问题。我是XML的绝对主义者。

2 个答案:

答案 0 :(得分:1)

使用相同方法的一种可能方式:

string a = 
    xnodePagedata.SelectSingleNode("//control[@id='busRowOAppr2EIDLookUpUserControl']/field/valuefield/@value")
                 .Value;

更新:

如果一个<valuefield>中有多个<control>并且您想要所有value,请使用SelectNodes(),例如:

var values =
    xPagedata.SelectNodes("//control[@id='busRowOAppr2EIDLookUpUserControl']/field/valuefield/@value");
foreach (XmlNode value in values)
{
    Console.WriteLine(value.Value);
}

答案 1 :(得分:1)

您可以使用XDocument:使用Descendants("control")获取所有控件,然后使用Where子句对其进行过滤,然后使用SelectMany获取值域的值的展平集合。

XDocument doc = XDocument.Load(filepath);

var result = doc.Descendants("control")
                .Where(i => (string)i.Attribute("id") == "busRowOAppr2EIDLookUpUserControl")
                .SelectMany(i => i.Descendants("valuefield")
                                  .Select(j => j.Attribute("value")))
                .ToList();

这就是结果:

result  Count = 2    
[0] {value="709227"}    
[1] {value="_JohnDoe@Wonder.com"}
相关问题