【问题标题】:get contents from inner xml with xml parsing in c#?在c#中使用xml解析从内部xml获取内容?
【发布时间】:2016-03-09 01:36:44
【问题描述】:

我有一项服务将以下 xml 作为字符串返回。我正在使用 Xdocument 解析方法和 XmlDocument 加载方法将字符串转换为 xml。但我想解析并获取我需要用于进一步处理的状态和 i_numer。有人可以指出我正确的方向或给出一些提示。下面是我正在使用的 xml。

我尝试了 Xdocument 和 XmlDocument 中的 innerxml 属性,它返回整个 "" 元素,这不是我需要的。

<Report>
    <Incidentreport Company="company1" ID="sample">
       <status i_number="12345678" status="sucessful" />
    </Incidentreport>
</Report>

【问题讨论】:

标签: c# xml xml-parsing


【解决方案1】:

以下应该有效:

string str = [string of xml goes here];
string i_number = string.Empty;
XmlDocument doc = new XmlDocument();
doc.Load(str);
XmlNode node = doc.SelectSingleNode("//status");
i_number = node.Attributes["i_number"].Value;

【讨论】:

    【解决方案2】:

    您可以使用接受XPath参数的SelectSingleNode()一次性获取目标属性值*:

    var raw = @"<Report>
        <Incidentreport Company='company1' ID='sample'>
           <status i_number='12345678' status='sucessful' />
        </Incidentreport>
    </Report>";
    var doc = new XmlDocument();
    doc.LoadXml(raw);
    var result = doc.SelectSingleNode("/Report/Incidentreport/status/@i_number");
    Console.WriteLine(result.Value);
    

    dotnetfiddle demo

    *) 请注意如何在 XPath 中使用 @attribute_name 语法来引用 XML 属性

    【讨论】:

      猜你喜欢
      • 2011-06-29
      • 1970-01-01
      • 2013-08-30
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 2016-03-21
      相关资源
      最近更新 更多