[英]Parsing Complex XML using LINQ
I have CDA XML I am trying to parse and query it using LINQ. 我有CDA XML,我正在尝试使用LINQ进行解析和查询。 However, I am unable to retrieve the values. 但是,我无法检索这些值。
I am trying the following LINQ code: 我正在尝试以下LINQ代码:
var cdafile = XDocument.Load("cda.xml");
var patientCity = from c in cdafile.Elements("recordTarget")
.Elements("patientRole")
.Elements("addr")
select (string)c.Element("city").Value;
I am getting empty value in patientCity
. 我在patientCity
得到了空值。 Am I doing something wrong? 难道我做错了什么?
<?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>
You need to include default namespace in your query ( urn:hl7-org:v3
) and query Root
property of XDocument
: 您需要在查询( 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;
This is because Elements
searches direct children of node (which in case of XDocument
would be document itself with its only direct children of ClinicalDocument
). 这是因为Elements
搜索的是节点的直接子代 (在XDocument
情况下,它将是其自身具有ClinicalDocument
唯一直接子代的文档本身)。
You can use Descendants
to search any descendants of current node, ignoring hierarchical walking altogether: 您可以使用Descendants
搜索当前节点的任何后代,而完全不考虑层次结构的遍历:
var patientCity = from c in cdafile.Descendants(ns + "city") select c.Value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.