简体   繁体   中英

get xml node value using c#

I have a problem where I need to get the value of a specific node in c#

I have this sample XML-Code and here is my C# code

    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

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.

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.

Console.WriteLine( rdr.ReadInnerXml());

In the following question, you want to deal with larger Xml . I prefer Linq to Xml when dealing with larger set.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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