【问题标题】:How to Read XML in .NET?如何在 .NET 中读取 XML?
【发布时间】:2011-06-12 18:34:27
【问题描述】:

XML 新手在这里! 所以我有一些xml数据:

<DataChunk>
    <ResponseChunk>
        <errors>
            <error code=\"0\">
                Something happened here: Line 1, position 1.
            </error>
        </errors>
    </ResponseChunk>
</DataChunk>

我如何获得“错误”列表,我可以在其中访问“错误代码”和下面的文本描述......? 另外,我在 c# 中使用 .net4.0...谢谢!

【问题讨论】:

  • 我假设:´ ´ 不是您的 XML 实际的样子吗?那些斜线会破坏它,它只是C#转义你已经剪切和粘贴了吗?
  • @james 是的 >.

标签: c# xml


【解决方案1】:

将 XML 加载到 XmlDocument 中,然后使用 xpath 查询来提取您需要的数据。

例如

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

XmlNode errorNode = doc.DocumentElement.SelectSingleNode("/DataChunk/ResponseChunk/Errors/error");

string errorCode = errorNode.Attributes["code"].Value;
string errorMessage = errorNode.InnerText;

如果 XML 可能包含多个错误元素,您可以使用 SelectNodes 获取包含该 xpath 中所有元素的 XmlNodeList。例如:

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

XmlNodeList errorNodes = doc.DocumentElement.SelectNodes("/DataChunk/ResponseChunk/Errors/error");

foreach(XmlNode errorNode in errorNodes)
{
  string errorCode = errorNode.Attributes["code"].Value;
  string errorMessage = errorNode.InnerText;
}

选项 2

如果您有 XML 的 XML 架构,您可以将架构绑定到一个类(使用 .NET xsd.exe 工具)。一旦你有了它,你就可以将 XML 反序列化为一个对象,并从该对象而不是原始 XML 中使用它。这本身就是一个完整的主题,因此如果您确实有架构,则值得研究。

【讨论】:

  • 你有 SelectSingleNode,而 OP 想要一个 error 节点的列表。
  • @Gabe :但我也有“如果 XML 有可能具有多个错误元素,您可以使用 SelectNodes 获取包含该 xpath 中所有元素的 XmlNodeList。” - 但是为多个错误节点添加了示例代码。
  • @joey : 这就是我半张贴在沙发上看电视的结果:)
【解决方案2】:

你可以使用Linq to XML:

var doc = XDocument.Parse(xml);
var errors = from e in doc.Descendants("error")
             select new
             {
                code = e.Attribute("code").Value,
                msg = e.Value.Trim()
             };

foreach (var e in errors)
{
    // use e.code & e.msg
}

但是,如果您的输入 XML 非常大,最好使用 XMLReader 浏览文档。

【讨论】:

    【解决方案3】:
    XmlReader xmlReader = XmlReader.Create(new StringReader(response));
            AmortizationCalculatorBE amortization = new AmortizationCalculatorBE();
    List<PaymentCalculator> paymentList = new List<PaymentCalculator>();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(new StringReader(response));
            XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("response/amortizationschedule/payment");
            XmlNodeList nodeList2 = xmlDoc.DocumentElement.SelectNodes("response");
            foreach (XmlNode node in nodeList)
            {
                PaymentCalculator payment = new PaymentCalculator();
                payment.beginningbalance = node.SelectSingleNode("beginningbalance").InnerText;
                payment.principal = node.SelectSingleNode("principal").InnerText;
                payment.interest = node.SelectSingleNode("interest").InnerText;
                paymentList.Add(payment);
    
            }
            amortization._PaymentCalculator = paymentList;
            foreach (XmlNode node in nodeList2)
            {
                amortization.totalprincipal = node.SelectSingleNode("totalprincipal").InnerText;
                amortization.totalinterest = node.SelectSingleNode("totalinterest").InnerText;
    
            }
    

    【讨论】:

      【解决方案4】:

      使用SelectNodesCastIEnumerable&lt;XmlElement&gt; 类型集合。那么您可以尝试使用linq 获取您的价值。

      XmlDocument doc = new XmlDocument();
      doc.LoadXml(xml_str);
      var errors = doc
                  .SelectNodes("/DataChunk/ResponseChunk/Errors/error")
                  .Cast<XmlElement>()
                  .Select(x => new {
                               errorCode = x.Attributes["code"].Value,
                               errorMessage = x.InnerText
                          });
      
      foreach (var item in errors)
      {
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多