如何使用 Xpath 在 C# 中读取 XML [英] How to read XML in C# using Xpath

查看:31
本文介绍了如何使用 Xpath 在 C# 中读取 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 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>
    <GetSKUsPriceAndStockResponse xmlns="http://tempuri.org/">
      <GetSKUsPriceAndStockResult>
        <RequestStatus>
          <DateTime>2/28/2012 5:28:05 PM</DateTime>
          <Message>S200</Message>
        </RequestStatus>
        <SKUsDetails>
          <SKUDetails>
            <SKU>N82E16834230265</SKU>
            <Model>X54C-NS92</Model>
            <Stock>true</Stock>
            <Domain>newegg.com</Domain>
            <SalePrice>439.99</SalePrice>
            <ShippingCharge>0.00</ShippingCharge>
            <Currency>USD</Currency>
          </SKUDetails>
        </SKUsDetails>
      </GetSKUsPriceAndStockResult>
    </GetSKUsPriceAndStockResponse>
  </soap:Body>
</soap:Envelope>

如何使用 XPath 读取 节点?.上面 XML 的 XNamespace 是什么?

How can I read <SKUDetails> Node using XPath?. What will be XNamespace for above XML?

推荐答案

使用 XPath 和 XmlDocument (C#) 操作 XML 数据

最好使用 LINQ toXML,因为您使用的是 .net 4.0,无需学习 XPath 来遍历 xml 树.

its better to use LINQ to XML as your are using .net 4.0 and there is no need to learn XPath to traverse the xml tree.

不确定 xpath 表达式,但您可以像这样编码

Not sure about the xpath expression but you can code like this

string fileName = "data.xml";
XPathDocument doc = new XPathDocument(fileName);
XPathNavigator nav = doc.CreateNavigator();

// Compile a standard XPath expression
XPathExpression expr; 
expr = nav.Compile("/GetSKUsPriceAndStockResponse/GetSKUsPriceAndStockResult/SKUsDetails/SKUDetails");
XPathNodeIterator iterator = nav.Select(expr);
try
{
  while (iterator.MoveNext())
  {

  }
}
catch(Exception ex) 
{
   Console.WriteLine(ex.Message);
}

这篇关于如何使用 Xpath 在 C# 中读取 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆