简体   繁体   English

使用C#获取xml节点值

[英]get xml node value using c#

I have a problem where I need to get the value of a specific node in c# 我有一个问题需要在C#中获取特定节点的值

I have this sample XML-Code and here is my C# code 我有此示例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);
                    }
                }
            }

The desired output is 所需的输出是

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

including the Text Node. 包括文本节点。 How can i do that? 我怎样才能做到这一点? thank you 谢谢

I also need to loop a huge xml file 我还需要循环一个巨大的xml文件

and I need to get the value of a specific node 我需要获取特定节点的值

and I need to skip some specific node also. 而且我还需要跳过一些特定的节点。 example I have a node. 例子我有一个节点。 the program must not read that Node and its childen Node. 程序不得读取该节点及其子节点。

How can i do that? 我怎样才能做到这一点?

<ChapterHeader>
    <Text> I need to get the text here</Text>
</ChapterHeader>
<Blank>
    <Not>
    </Not>
</Blank>

System.Xml.Linq is a newer library designed to get rid of undesired reader style. System.Xml.Linq是一个较新的库,旨在摆脱不需要的阅读器样式。

var document = XDocument.Parse(xml);
var texts = document.Descendants("Text");

foreach (var text in texts)
{
    Console.WriteLine(text);
}

The desired output is 所需的输出是

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

Look for ReadInnerXml which reads all the content, including markup, as a string. 查找ReadInnerXml ,它将所有内容(包括标记)读取为字符串。

Console.WriteLine( rdr.ReadInnerXml());

In the following question, you want to deal with larger Xml . 在以下问题中,您要处理更大的Xml I prefer Linq to Xml when dealing with larger set. 处理较大的集合时,我更喜欢Linq而不是Xml

The program must not read that Node and its childen Node 程序不得读取该节点及其子节点

Yes, it is possible. 对的,这是可能的。 You could do something like this. 你可以做这样的事情。

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.

Check this Example 检查这个Example

您可以使用与您使用的解析样式相同的样式( rdr.LocalName = "Text" ),然后使用rdr.ReadOuterXml()

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

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