【问题标题】:c# Reading data from XMLc# 从 XML 中读取数据
【发布时间】:2018-04-23 09:32:19
【问题描述】:

我对如何从 XML 读取数据有问题。 XML 看起来像这样:

<PosXML version="7.2.0">
    <ReadCardResponse>
        <ReturnCode>1</ReturnCode>
        <Card>
            <Pan>222300******5062</Pan>
            <Expires>****</Expires>
            <CardName>MASTERCARD</CardName>
            <CardSource>2</CardSource>
        </Card>
    </ReadCardResponse>
</PosXML>

我已经从流中加载了 XML:

XDocument doc;
using (Stream responseStream = httpResponse.GetResponseStream())
{
    doc= XDocument.Load(responseStream);
}

试过了,还是不行:

XElement returnCode = doc.XPathSelectElement("ReturnCode")

【问题讨论】:

  • XPath ReturnCode 无效。对于您的 XML,XPath 应该类似于(未经测试的)ReadCardResponse\ReturnCode。您可以查看 XPath 文档以了解更复杂的 XPath 查询
  • 阅读XPath Expressions。 XPath 表达式可用于选择任何节点或属性。然后,您可以将 SelectNodesSelectSingleNode 与 XPath 表达式一起使用到要读取的节点。

标签: c# xml linq-to-xml


【解决方案1】:
var returnCode = doc.XPathSelectElement(@"PosXML/ReadCardResponse/ReturnCode");

你需要使用元素的完整路径

【讨论】:

    【解决方案2】:

    试试:

    XElement returnCode = doc.Element("ReadCardResponse").Element("ReturnCode")
    

    您还可以通过XPathnodes 或一些linq 查询访问元素。尝试使用你的 IDE 的智能感知

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2014-03-14
      相关资源
      最近更新 更多