Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all text nodes from XML file

Tags:

c#

xml

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
like image 522
AML Avatar asked Dec 02 '22 21:12

AML


2 Answers

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.

like image 105
gwiazdorrr Avatar answered Dec 11 '22 15:12

gwiazdorrr


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 :)

like image 42
sam1589914 Avatar answered Dec 11 '22 16:12

sam1589914