C# 使用LINQ解析复杂XML
我知道我正在尝试使用LINQ解析和查询它。但是,我无法检索这些值 我正在尝试以下LINQ代码:C# 使用LINQ解析复杂XML,c#,linq,linq-to-xml,C#,Linq,Linq To Xml,我知道我正在尝试使用LINQ解析和查询它。但是,我无法检索这些值 我正在尝试以下LINQ代码: var cdafile = XDocument.Load("cda.xml"); var patientCity = from c in cdafile.Elements("recordTarget") .Elements("patientRole") .Ele
var cdafile = XDocument.Load("cda.xml");
var patientCity = from c in cdafile.Elements("recordTarget")
.Elements("patientRole")
.Elements("addr")
select (string)c.Element("city").Value;
我在patientCity
中得到空值。我做错什么了吗
<?xml version="1.0" encoding="UTF-8"?>
<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:sdtc="urn:hl7-org:sdtc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:hl7-org:v3 http://xreg2.nist.gov:8080/hitspValidation/schema/cdar2c32/infrastructure/cda/C32_CDA.xsd">
<realmCode code="US"/>
<title>Cypress C32 Patient Test Record: Nelson Tuff</title>
<recordTarget>
<patientRole>
<id root="Cypress" extension="4fe1ecbca9ffcc03cd0004e3"/>
<addr use="HP">
<streetAddressLine>202 Burlington Rd.</streetAddressLine>
<city>Bedford</city>
<state>MA</state>
<postalCode>01730</postalCode>
</addr>
<telecom value="tel:+1-781-271-3000"/>
<patient>
<name>
<given>George</given>
<family>Mathew</family>
</name>
</patient>
</patientRole>
</recordTarget>
</ClinicalDocument>
Cypress C32患者测试记录:Nelson Tuff
伯灵顿路202号。
贝德福德
文科硕士
01730
乔治
马修
您需要在查询中包括默认名称空间(urn:hl7 org:v3
)和XDocument
的查询Root
属性:
XNamespace ns = "urn:hl7-org:v3";
var patientCity =
from c in cdafile.Root
.Elements(ns + "recordTarget")
.Elements(ns + "patientRole")
.Elements(ns + "addr")
select (string)c.Element(ns + "city").Value;
这是因为Elements
搜索节点的直接子节点(在XDocument
的情况下,它将是文档本身及其ClinicalDocument
的唯一直接子节点)
您可以使用子体
搜索当前节点的任何子体,完全忽略分层遍历:
var patientCity = from c in cdafile.Descendants(ns + "city") select c.Value;
可能重复的(加上相关的)