【问题标题】:How to get element by element from XmlDocument如何从 XmlDocument 中逐个元素地获取元素
【发布时间】:2023-03-05 13:00:02
【问题描述】:

我能够从这个列表中获得我的第一个元素

 <?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <GetITARListResponse xmlns="http://tempuri.org/">
      <GetITARListResult>
        <ClassificationCode>
          <code>dsd</code>
          <description>toto</description>
          <legislation>d/legislation>
        </ClassificationCode>
        <ClassificationCode>
          <code>dsd</code>
          <description>tata</description>
          <legislation>dsd</legislation>
        </ClassificationCode>
        <ClassificationCode>
          <code>code2</code>
          <description>dsds</description>
          <legislation>dsd</legislation>
        </ClassificationCode>

通过写作

XDocument result = new XDocument();
result  =   ExportControl.ResultXML;
var codes = HttpContext.Current.Server.MapPath("~/XML_Templates/codes.xml");
dynamic root = new ExpandoObject();
XmlToDynamic.Parse(root, xDoc.Elements().First());
var result = xDoc.Descendants(XNamespace.Get("http://tempuri.org/") + "code").First();

获得第一个代码“dsd”。但是,如果我想要一个 foreach 并获取所有代码怎么办?或者如果我想要某个代码怎么办?例如

var result = xDoc.Descendants(XNamespace.Get("http://tempuri.org/") + "code")[2]

【问题讨论】:

标签: c# xml xml-parsing linq-to-xml


【解决方案1】:

.Net 框架提供了一组可用于移动 XML 文件的工具:

  1. XmlReader:该类以分层方式读取xml文件,只转发 没有缓存。
  2. XmlWriter:这个类只在xml文件中写入,没有 缓存。
  3. XmlDocument:它可以帮助您浏览和编辑小文档,因为它是 比 XmlReader/Writer 慢。它使用 XmlNode 对象在您的文档中移动并执行更改(属性)。编辑后您可以保存。一种很好的导航方式是使用 XPath (xml 的查询语言)。
  4. XPathNvigator:类提供了一种在 XML 文档中导航的简单方法。

在您的情况下,我的建议是分别使用 XmlReader 和 XPath 实现几种方法,一种用于迭代,另一种用于定位特定节点。

更新:这里的 XML 示例格式错误:

<legislation>d/legislation>

这显示了一个读取文件的示例:

using System;
using System.Xml;

namespace XMLTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                            <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                              <soap:Body>
                                <GetITARListResponse xmlns=""http://tempuri.org/"">
                                  <GetITARListResult>
                                    <ClassificationCode>
                                      <code>dsd</code>
                                      <description>toto</description>
                                      <legislation>d</legislation>
                                    </ClassificationCode>
                                    <ClassificationCode>
                                      <code>dsd</code>
                                      <description>tata</description>
                                      <legislation>dsd</legislation>
                                    </ClassificationCode>
                                    <ClassificationCode>
                                      <code>code2</code>
                                      <description>dsds</description>
                                      <legislation>dsd</legislation>
                                    </ClassificationCode>
                                  </GetITARListResult>
                                </GetITARListResponse>
                              </soap:Body>
                            </soap:Envelope>";

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            var items = doc.GetElementsByTagName("ClassificationCode");

            foreach (var item in items)
            {
                Console.WriteLine(((System.Xml.XmlElement)(item)).InnerText.ToString());
            }
            Console.ReadLine();
        }
    }
}
// OUTPUT
// dsdtotod
// dsdtatadsd
// code2dsdsdsd

【讨论】:

  • 您忽略了 OP 已经使用的 XDocument 系列。
  • @Robert 感谢您提供这些有用的信息,至于拼写错误,那是因为我删除了代码(机密代码)并且错误地删除了
【解决方案2】:

您的代码示例仅因为您调用 First() 方法而返回第一项。为了遍历所有代码,您可以跳过调用,您将获得一个 IEnumerable。然后你可以像这样循环:

var codes = result.Descendants(XNamespace.Get("http://tempuri.org/") + "code");

foreach (var codeElement in codes)
{
    Console.WriteLine(codeElement.Value);
}
// prints:
// dsd
// dsd
// code2

要通过索引访问它们,您可以像这样使用 ElementAt:

var someCode = codes.ElementAt(1);
Console.WriteLine(someCode.Value);  // prints dsd

或者您可以像这样按名称过滤:

var code2 = codes.Where(c => c.Value == "code2").First();
Console.WriteLine(code2.Value); // prints code2     

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多