如何通过标签元素搜索节点搜索

时间:2016-02-18 08:33:01

标签: c# xml parsing linq-to-xml

我有一个复杂的XML文件,我应该用C#语言解析它。

所以这是一个简单的部分:

<ClinicalDocument>
    <component>
    <section>
        <templateId root='2.16.840.1.113883.10.20.1.11'/> <!-- Problem section template -->
        <code code="11450-4" codeSystem="2.16.840.1.113883.6.1"/> 
        <title>Problems</title> 
        <text></text>
         .......
    </section>
    </component>
</ClinicalDocument>

现在我想搜索此XML文件的所有元素,其中templateId root =“2.x.x.x”。

我已经构建了这段代码但不起作用:

var doc = XDocument.Load(_xmlName);
            XElement element =
            doc.Element("section")
                .Descendants("templateId")
                .Where(a => a.Element("root").Value.Equals(_TEMPLATE_ID_PROBLEM))
                    .First();
  

修改

我已用此更改了我的代码:

var doc = XDocument.Load(_xmlName);
            XElement element =
            doc.Element("ClinicalDocument").Element("component").Element("section")
                .Descendants("templateId")
                .Where(a => a.Element("root").Value.Equals(_TEMPLATE_ID_PROBLEM))
                    .First();

但我有一个错误:

System.NullReferenceException was unhandled
  _HResult=-2147467261
  _message=Riferimento a un oggetto non impostato su un'istanza di oggetto.
  HResult=-2147467261
  IsTransient=false
  Message=Riferimento a un oggetto non impostato su un'istanza di oggetto.
  Source=XmlParser_Decipher
  StackTrace:
       in XmlParser_Decipher.Program.Main(String[] args) in c:\Users\michele.castriotta\Source\Workspaces\Omniacare\XmlParser_Decipher\XmlParser_Decipher\Program.cs:riga 19
       in System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       in System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       in Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       in System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       in System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       in System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

我试着这样做:

XElement element =
            doc.Element("ClinicalDocument");

并且var元素为null。

1 个答案:

答案 0 :(得分:0)

section是文档根目录的孩子:

doc.Root.Element("section")

root也不是元素 - 它是templateId元素的属性:

.Where(t => (string)t.Attribute("root") == _TEMPLATE_ID_PROBLEM)

完整查询将如下所示

doc.Root.Element("section")
   .Descendants("templateId") // you can use Elements here
   .Where(t => (string)t.Attribute("root") == _TEMPLATE_ID_PROBLEM)
   .First();

另一种选择是使用XPath:

doc.Root.XPathSelectElement($"section/templateId[@root='{_TEMPLATE_ID_PROBLEM}']");