在C#中读取XML值

时间:2012-10-30 07:15:48

标签: c# .net xml

我有XML文件,我想通过C#

中的xpath读取

我的XML看起来像:

<?xml version="1.0"?>
<doc>
     <members>
        <member test="testing" name="T:QuexstBase.Tools.RegistryHelper.RegistryHelper">
            <summary>
            RegistryHelper class to use registry operations.
            </summary>
        </member>
        <member test="testing" name="F:QuexstBase.Tools.RegistryHelper.RegistryHelper.baseKey">
            <summary>
            private member base key
            </summary>
        </member>
        <member  test="tester"  name="F:QuexstBase.Tools.RegistryHelper.RegistryHelper.subKey">
            <summary>
            default sub key
            </summary>
        </member>
    </members>
</doc>

我想阅读其值正在测试的 / members / member / @ test 。 我不想使用foreach或for循环。

3 个答案:

答案 0 :(得分:3)

var xDoc = XDocument.Parse(xml);//or XDocument.Load(fileName)
var members = xDoc.XPathSelectElements("//member[@test='testing']")
                  .ToList();

答案 1 :(得分:1)

var xml = @"<doc>
        <members>
        <member test=""testing"" name=""T:QuexstBase.Tools.RegistryHelper.RegistryHelper"">
            <summary>
            RegistryHelper class to use registry operations.
            </summary>
        </member>
        <member test=""testing"" name=""F:QuexstBase.Tools.RegistryHelper.RegistryHelper.baseKey"">
            <summary>
            private member base key
            </summary>
        </member>
        <member  test=""tester""  name=""F:QuexstBase.Tools.RegistryHelper.RegistryHelper.subKey"">
            <summary>
            default sub key
            </summary>
        </member>
    </members>
</doc>";

var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml));
var doc = new XPathDocument(ms);
var nav = doc.CreateNavigator();
var nodes = nav.Select("//member[@test='testing']");

更新:看一下这篇文章XDocument or XmlDocument

答案 2 :(得分:1)

尝试使用XmlDocument

XmlDocument document = new XmlDocument();
document.LoadXml("your xml string");
var nodes = document.SelectNodes("/members/member/@test");
//or for single node  
var node = document.SelectSingleNode("/members/member/@test");