2017-03-07 76 views
0

一个节点我上午XML字符串像下面提到:如何提取XML字符串C#

<?xml version="1.0" encoding="utf-8" ?> 
<NodeA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.air-watch.com/webapi/resources"> 
    <AdditionalInfo> 
     <Links> 
      <Link xsi:type="link"> 
      </Link> 
     </Links> 
    </AdditionalInfo> 
    <TotalResults>100</TotalResults> 
    <NodeB> 
     <NodeC> 
      <Id>1</Id> 
      <A>valueA</A> 
      <B>valueB</B> 
     </NodeC> 
     <NodeC> 
      <Id>2</Id> 
      <A>valueA</A> 
      <B>valueA</B> 
     </NodeC> 
    </NodeB> 
</NodeA> 

我想提取NodeB和它的子节点(NODEC元素)。我该怎么做?下面的解决方案确实有点类似操作,但它需要的XML字符串中的XDocument首先被加载:

XDocument doc=XDocument.Parse(xmlstr); 
String response=doc.Elements("question") 
        .Where(x=>x.Attribute("id")==id) 
        .Single() 
        .Element("response") 
        .Value; 

有没有办法做到这一点,而无需将其加载到一个文档?对字符串对象本身的一些操作。

+5

你为什么要避免使用'XDocument'?字符串操作不是基于XML的。你想要一个XML API。 LINQ to XML是一个很好的XML API。 –

+0

xdocument或字符串,你仍然在内存中存储整个事情。为什么限制? – tinstaafl

+0

嗯,如果避免加载到一个XDocument没有任何记忆或性能的差异,我想我会继续前进,这样做。 – tavier

回答

-1

你为什么不能使用这个

XDocument doc=XDocument.Parse(xmlstr); 
String response=doc.Elements("question") 
        .Where(x=>x.Attribute("id")==id) 
        .Single() 
        .Element("response") 
        .Value; ? 

你可以使用正则表达式即可。

+0

我仍然无法获得我感兴趣的节点。您能否将最终的Linq发布到XML? – tavier