简体   繁体   English

如何从xml字符串C#中提取节点

[英]How to extract a node from xml string C#

I have am xml string like mentioned below: 我有一个xml字符串,如下所述:

<?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>

I want to extract NodeB and its child nodes (NodeC elements). 我想提取NodeB及其子节点(NodeC元素)。 How can I do it? 我该怎么做? Below solution does somewhat similar operation but it needs the xml string to be loaded in a XDocument first: 下面的解决方案做了一些类似的操作,但是它需要首先将xml字符串加载到XDocument中:

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

Is there a way to do it without having to load it in a doc? 有没有一种方法可以不必将其加载到文档中? Some operation on string object itself. 对字符串对象本身的一些操作。

Why cant you use this 你为什么不能使用这个

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

you can use Regular Expressions then. 您可以使用正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM