【问题标题】:Reading and iterating through xml elements in C#在 C# 中读取和遍历 xml 元素
【发布时间】:2015-01-28 01:39:05
【问题描述】:

我刚刚开始使用 C# 语言并寻找一种方法来遍历 xml 文件中的元素和子元素。

我的 xml 看起来像这样-

  <ServerList>
     <server name = "serverName1" username ="username" password ="password">
      <serviceName>serviceName</serviceName>
      <serviceName>serviceName</serviceName>
      <serviceName>serviceName</serviceName>
   </server>
<server name = "serverName2" username ="username" password = "password">
       <serviceName>serviceName</serviceName>
       <serviceName>serviceName</serviceName>
  </server>
<ServerList>

我只是在寻找一种方法,我可以遍历第一个服务器元素及其子元素,而不是下一个服务器元素及其子元素。

【问题讨论】:

标签: c# xml


【解决方案1】:

您可以直接使用 LINQ to XML:

XDocument xdoc = XDocument.Load("myXmlFile.xml");

var servers = xdoc.Descendants("server"); 
for (var server in servers) 
{
    var children = server.Elements(); 
    for (var child in children)
    {
        // Do what you want with the server and child here
    }
}

如果您需要更多信息,您可能需要考虑使用 XML 反序列化。这将允许您定义映射到 XML 模式中的节点的类,将 XML 反序列化为强类型对象图,然后您可以对其进行迭代、过滤、转换等。如果您决定采用这种方法,我建议使用 @ 987654321@,因为 BCL XML 序列化器有点烂。

【讨论】:

  • 这是 100% 错误的,它只会返回 children (servicenames) 而不是 attributes 像 (name, usernamepassword)
  • @FarhangAmary server 是一个 XElement 对象。请参阅XElement 上的 MSDN 文档,了解如何访问与 XML 文档中的元素对应的属性、子代、后代和其他数据。
  • 是的,Asad 没错,我稍微修改了你的代码,我也能够检索到属性
  • @FarhangAmary 例如,要获取name 属性的值,您可以使用server.Attribute("name").Value
  • @FarhangAmary 我只是在解释如何访问您在评论中提到的server 节点的属性。关于“我告诉你的答案不完整”,我的答案到底缺少什么?
【解决方案2】:

后代很好,反正这里是递归的方法

class Program
{
    static void Main(string[] args)
    {
        XElement x = XElement.Load("XMLFile1.xml");
        recursive(x.Elements());
        Console.ReadKey();
    }

    private static void recursive(IEnumerable<XElement> elements)
    {
        foreach (XElement n in elements)
        {
            Console.WriteLine(n.Name);
            Console.WriteLine("--");
            if (n.Descendants().Any())
            {
                recursive(n.Elements());
            }
            else
            {
             Console.WriteLine(n.Value.ToString());// End of node (leaf)
            }
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-23
    • 2022-06-11
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多