从XML中检索值

时间:2017-08-25 12:48:49

标签: c# xml linq

这是我的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<PutUserLinkRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <request xmlns="http://tempuri.org">
    <id S="ID-KMEHR" SV="1.0" SL="">Delta.PutUserLink.25/08/2017 13:07:43</id>
    <author>
      <hcparty>
      </hcparty>
    </author>
  </request>
  <userlink xmlns="http://tempuri.org">
    <user1>
      <cd S="CD-USERTYPE" SV="1.0" SL="" DN="" L="fr">patient</cd>
      <patient>
        <id S="ID-PATIENT" SV="1.0" SL="">97031038713</id>
      </patient>
    </user1>
    <user2>
    </user2>
    <type S="CD-USERLINK" SV="1.0" SL="" DN="" L="fr">patientassent</type>

  </userlink>
</PutUserLinkRequest>

我无法检索值97031038713

XmlDocument _xmlDoc = new XmlDocument();

_xmlDoc.LoadXml(_mRec.Content);

XmlNamespaceManager manager = new XmlNamespaceManager(_xmlDoc.NameTable);
manager.AddNamespace("ns","http://tempuri.org");

然后我尝试了不同的事情,但没有成功

`<?xml version="1.0" encoding="utf-8"?>
<PutUserLinkRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <request xmlns="http://tempuri.org">
    <id S="ID-KMEHR" SV="1.0" SL="">Delta.PutUserLink.25/08/2017 13:07:43</id>
    <author>
      <hcparty>
      </hcparty>
    </author>
  </request>
  <userlink xmlns="http://tempuri.org">
    <user1>
      <cd S="CD-USERTYPE" SV="1.0" SL="" DN="" L="fr">patient</cd>
      <patient>
        <id S="ID-PATIENT" SV="1.0" SL="">97031038713</id>
      </patient>
    </user1>
    <user2>
    </user2>
    <type S="CD-USERLINK" SV="1.0" SL="" DN="" L="fr">patientassent</type>

  </userlink>
</PutUserLinkRequest>

1 个答案:

答案 0 :(得分:0)

您可以使用LINQ to XML轻松完成此任务:

var doc = XDocument.Parse(xml);

XNamespace ns = "http://tempuri.org";

var id = (string) doc.Descendants(ns + "patient")
    .Elements(ns + "id")
    .Single();

请参阅this fiddle了解演示。