使用C#获取xml节点值

零问

我有一个问题需要在C#中获取特定节点的值

我有这个样本XML-Code,这是我的C#代码

    string xml = @"
            <ChapterHeader>
        <Text> I need to get the text here</Text>
    </ChapterHeader>
            ";
XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
            while (rdr.Read())
            {
                if (rdr.NodeType == XmlNodeType.Element)
                {
                    Console.WriteLine(rdr.LocalName);
                    if (rdr.LocalName == "ChapterHeader")
                    {
                        Console.WriteLine(rdr.Value);
                    }
                }
            }

所需的输出是

<Text> I need to get the text here</Text>

包括文本节点。我怎样才能做到这一点?谢谢你

我还需要循环一个巨大的xml文件

我需要获取特定节点的值

而且我还需要跳过一些特定的节点。例子我有一个节点。程序不得读取该节点及其子节点。

我怎样才能做到这一点?

<ChapterHeader>
    <Text> I need to get the text here</Text>
</ChapterHeader>
<Blank>
    <Not>
    </Not>
</Blank>
哈里·普拉萨德(Hari Prasad)

所需的输出是

<Text> I need to get the text here</Text>

查找ReadInnerXml哪个以字符串形式读取所有内容(包括标记)。

Console.WriteLine( rdr.ReadInnerXml());

在以下问题中,您要处理large Xml我喜欢LinqXml有更大的一组的时候。

程序不得读取该节点及其子节点

是的,有可能。你可以做这样的事情。

XDocument doc = XDocument.Load("filepath");

var nestedElementValues = 
doc.Descendants("ChapterHeader")    // flattens hierarchy and look for specific name.
   .Elements()                      // Get elements for found element
   .Select(x=>(string)x.Value);     // Read the value.

检查一下 Example

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章