views:

234

answers:

1

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

A: 

Oops - nevermind.

I changed Xpath to this: string strXPath = "/myroot/*[local-name()='group3' and namespace-uri()='myGroup3SerializerStyle']";

and it worked. The idea was to add lastname at the same level as firstname, not under firstname.

The correct desired output was really this:

resultOuter=<myroot><group3 xmlns="myGroup3SerializerStyle"><firstname xmlns=""
>Neal3</firstname><lastname xmlns="">New-Value</lastname></group3></myroot>

Neal

NealWalters