I want to get all text nodes from an XML file.
How can I do this?
Example Input:
<root>
<slide>
<Image>hi</Image>
<ImageContent>this</ImageContent>
<Thumbnail>is</Thumbnail>
<ThumbnailContent>A</ThumbnailContent>
</slide>
</root> 
Expected Output:
hi this is A
                The only solution (so far) to enumerate all text nodes in any xml, regardless of its structure:
string input = @"
    <root>
        <slide>
            <Image>hi</Image>
            <ImageContent>this</ImageContent>
            <Thumbnail>is</Thumbnail>
            <ThumbnailContent>A</ThumbnailContent>
        </slide>
    </root>";
foreach (XText text in (IEnumerable)XDocument.Parse(input).XPathEvaluate("//*/text()"))
{
    Console.WriteLine(text.Value);
}
EDIT: if you want to load xml from file then use XDocument.Load instead.
This code will print the inner text of all xml nodes which doesnt have a child:
    static void Main(string[] args)
    {
        XmlDocument x = new XmlDocument();
        x.Load("exp.xml");
        PrintNode(x.DocumentElement);
    }
    private static void PrintNode(XmlNode x)
    {
        if (!x.HasChildNodes)
            Console.Write(string.Format("{0} ", x.InnerText));
        for (int i = 0; i < x.ChildNodes.Count; i++)
        {
            PrintNode(x.ChildNodes[i]);
        }
    }
On your example XML it will result in the output you want :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With