vipin katiyar
vipin katiyar

Reputation: 3547

Append xml string into Existing xmlfile using c#

I have an xml like this :

<name>

<class>

</class>

</name>

then i want to add the tag like this

<tia:Demographic><Age/><DOB/></tia:Demographic>

in between

<class>

How can we do that .

i am using following code.

XDoc.LoadXml(@"<name><class></class></name>");   
XmlDocumentFragment xfrag = XDoc.CreateDocumentFragment(); 
 xfrag.InnerXml = @"<tia:Demographic><Age/><DOB/></tia:Demographic>";
 XDoc.DocumentElement.FirstChild.AppendChild(xfrag); 
XDoc.Save(@"D:\test.xml");

but it throws an error that tia: not a registered namespace

Upvotes: 0

Views: 1240

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You will need to register a namespace:

class Program
{
    static void Main()
    {
        var xdoc = new XmlDocument();
        xdoc.LoadXml(@"<name><class></class></name>");
        xdoc.DocumentElement.SetAttribute("xmlns:tia", "http://tia.com");
        var node = xdoc.CreateElement("tia", "Demographic", "http://tia.com");
        var xfrag = xdoc.CreateDocumentFragment();
        xfrag.InnerXml = @"<Age/><DOB/>";
        node.AppendChild(xfrag);
        xdoc.DocumentElement.FirstChild.AppendChild(node);
        xdoc.Save(Console.Out);
    }
}

Upvotes: 2

Jude Cooray
Jude Cooray

Reputation: 19862

Register the namespace using a XmlNamespaceManager .

Upvotes: 4

Related Questions