user3680601
user3680601

Reputation: 21

removing "#text" while parsing xml and displaying node value

I have a program to display the node name and value like this

public void findAllNodes(XmlNode node)
{
    Console.Write("{0}:", node.Name);

    Console.WriteLine(node.Value);
    Console.WriteLine("{0}"," ");
    foreach (XmlNode n in node.ChildNodes)
        findAllNodes(n);
}

using this xml:

<application_data>
    <applicant_data type="primary"> 
        <first_name>VINNY</first_name> 
        <mi></mi> 
        <last_name>SSILVERLACE</last_name> 
        <ssn>666279999</ssn> 
        <dob>1973-06-27</dob> 
        <address type="current">
            <po_box_no></po_box_no> 
            <roural_route></roural_route> 
            <street_no>7690</street_no> 
            <street_name>KETTLEDRUMS</street_name> 
            <apt_no></apt_no> 
            <city>MILILANI TOWN</city> 
            <state>HI</state> 
            <zip_code>96789</zip_code> 
        </address>
    </applicant_data>
</application_data>

But for this code, while displaying the node values, it diplays like this

#text:("node value"). 

Can you suggest some way to delete "#text" from the node value?

Upvotes: 2

Views: 911

Answers (2)

Asad Ali
Asad Ali

Reputation: 684

private static void RecurseXmlDocument(XmlNode root)
{
    if (root is XmlElement)
    {
        Console.Write("\n" + root.Name + ": ");
        if (root.HasChildNodes) RecurseXmlDocument(root.FirstChild);
        if (root.NextSibling != null) RecurseXmlDocument(root.NextSibling);
    }
    else if (root is XmlText)
    {
        Console.Write(((XmlText)root).Value);
    }
    else if (root is XmlComment)
    {
        Console.Write(root.Value);
        if (root.HasChildNodes) RecurseXmlDocument(root.FirstChild);
        if (root.NextSibling != null) RecurseXmlDocument(root.NextSibling);
    }
}

I modified this according to your needs and it works just fine now. You're going to have to call it like this:

public static void Main()
{
    XmlDocument document = new XmlDocument();
    document.Load("File.xml");
    RecurseXmlDocument((XmlNode)document.DocumentElement);
    Console.ReadKey();
}

Upvotes: 1

Chuck Savage
Chuck Savage

Reputation: 11955

It has nothing to do with your xml, but with your node.Name statement.

If you look here you will see that, node.Name will print #text for text nodes every time. I'm not familiar enough with XmlNode to tell you how to get the tag name as you appear to be wanting. You could try Linq-To-Xml as someone commented.

Example:

public void findAllNodes(XElement node)
{
    Console.Write("{0}:", node.Name.ToString());

    Console.WriteLine(node.Value);
    Console.WriteLine("{0}"," ");
    foreach (XElement n in node.Elements())
        findAllNodes(n);
}

findAllNodes(XElement.Load(file));

Upvotes: 1

Related Questions