C# CreateElement method - how to add an child element with xmlns=""
- by NealWalters
How can I get the following code to add the element with "xmlns=''"?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string strXML =
"<myroot>" +
" <group3 xmlns='myGroup3SerializerStyle'>" +
" <firstname xmlns=''>Neal3</firstname>" +
" </group3>" +
"</myroot>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strXML);
XmlElement elem = xmlDoc.CreateElement(null, "lastname", null);
elem.InnerText = "New-Value";
string strXPath = "/myroot/*[local-name()='group3' and namespace-uri()='myGroup3SerializerStyle']/firstname";
XmlNode insertPoint = xmlDoc.SelectSingleNode(strXPath);
insertPoint.AppendChild(elem);
string resultOuter = xmlDoc.OuterXml;
Console.WriteLine("\n resultOuter=" + resultOuter);
Console.ReadLine();
}
}
}
My current output:
resultOuter=<myroot><group3 xmlns="myGroup3SerializerStyle"><firstname xmlns=""
>Neal3<lastname>New-Value</lastname></firstname></group3></myroot>
The desired output:
resultOuter=<myroot><group3 xmlns="myGroup3SerializerStyle"><firstname xmlns=""
>Neal3<lastname xmlns="">New-Value</lastname></firstname></group3></myroot>
For background, see related posts:
http://www.stylusstudio.com/ssdn/default.asp?fid=23 (today)
http://stackoverflow.com/questions/2410620/net-xmlserializer-to-element-formdefaultunqualified-xml (March 9, thought I fixed it, but bit me again today!)