Inserting Xml Node and maintaining the prefix

G

GR

Hi,
I have something like the following:
(Please note this not actual code and it's very rough)

string source = "<abc:Root
xmlns:abc="http://mynamespace.com><abc:Record/></abc:Root>"
XmlDocument doc = new XmlDocument();
doc.LoadXml(source);

I now want to add a node such as the following:
XmlDocument tempDoc = new XmlDocument();
tempDoc.LoadXml("<abc:Order/>");
doc.FirstChild.FirstChild.AppendChild(tempDoc.FirstChild);

But when I do this the "abc:" is stripped out of the xml.
What I'm after is to add a new node to the 'doc' document and for it to
have the "abc:" prefix. I've tried various ways (create nodes, create
document fragment, create xmldoc etc) but all the methods I've tried so
far either strip the "abc:", crash or include the "abc:" but also with
the entire namespaceuri (which I dont want either).

So I have the following:
"<abc:Root xmlns:abc="http://mynamespace.com><abc:Record/></abc:Root>"

Now using C# I want to add a new node so that the doc.OuterXml looks
like the following:
"<abc:Root
xmlns:abc="http://mynamespace.com><abc:Record><abc:Order/></abc:Record></abc:Root>"

If possible please post a full code snippet.
Thanks
 
M

Martin Honnen

GR said:
string source = "<abc:Root
xmlns:abc="http://mynamespace.com><abc:Record/></abc:Root>"
XmlDocument doc = new XmlDocument();
doc.LoadXml(source);

What I'm after is to add a new node to the 'doc' document and for it to
have the "abc:" prefix.

It is simple, just use a namespace aware overload of CreateElement and
pass in the namespace URI you want to create the element in e.g.


string source =
"<abc:Root xmlns:abc=\"http://mynamespace.com\"><abc:Record/></abc:Root>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(source);

XmlElement order = doc.CreateElement("abc:Order",
doc.DocumentElement.NamespaceURI);
doc.DocumentElement.AppendChild(order);
doc.Save(Console.Out);

Result is

<abc:Root xmlns:abc="http://mynamespace.com">
<abc:Record />
<abc:Order />
</abc:Root>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top