Add attributes using XAttribute

269 views Asked by At

I have a root XML which is like this:

<Root xmlns="http://schemas.datacontract.org/2004/07/" xmlns:t="http://www.w3.org/2001/XMLSchema-instance">
   <Element1>somevalue</Element1>
   <Data/>
<Root>    

I need to add few customer related informaiton like (Name, Age etc) under Data Element Node. So, the result I expect is follows:

<Root xmlns="http://schemas.datacontract.org/2004/07/" xmlns:t="http://www.w3.org/2001/XMLSchema-instance">
   <Element1>somevalue</Element1>
   <Data>
     <Name t:type="xs:string" xmlns="" xmlns:s="http://www.w3.org/2001/XMLSchema">Elvis</Name>
     <Address t:type="xs:string" xmlns="" xmlns:s="http://www.w3.org/2001/XMLSchema">Some address</Address>
   </Data>
<Root>

How can I achieve this? I am using C#, .net 4.0.

I was trying out the below code, but didn't get the result I was expecting:

string strTemplate = "<Root xmlns='http://schemas.datacontract.org/2004/07/' xmlns:t='http://www.w3.org/2001/XMLSchema-instance'><Element1>somevalue</Element1><Data/></Root>";

        XDocument doc = XDocument.Parse(strTemplate);
        XElement rootElement = doc.Root;

        XElement dataElement = null;




        foreach (XElement descendant in rootElement.Descendants())
        {
            if (descendant.Name.LocalName == "Data")
            {
                dataElement = descendant;
                break;
            }
        }


        string cusData = "<CustData><Name>Elvis</Name><Address>XYZ</Address></CustData>";
        XElement customerElements = XElement.Parse(cusData);

        if (dataElement != null)
        {
            foreach (XElement custAttributes in customerElements.Descendants())
            {
                XNamespace t = "http://www.w3.org/2001/XMLSchema-instance";
                var attribute = new XAttribute(t + "type", "xs:string");
                 var attribute1 = new XAttribute(XNamespace.Xmlns + "s", "http://www.w3.org/2001/XMLSchema");
                XElement element = new XElement(custAttributes.Name, attribute, attribute1);
                element.Value = custAttributes.Value;

                dataElement.Add(element);
            }

        }
   string strPayload = doc.ToString();

When I execute the code I get the following:

<Data xmlns="http://schemas.datacontract.org/2004/07/">
  <Name t:type="xs:string" xmlns:t="http://www.w3.org/2001/XMLSchema-instance"   xmlns="">Elvis</Name>
  <Address t:type="xs:string" xmlns:t="http://www.w3.org/2001/XMLSchema-instance" xmlns="">XYZ</Address>
</Data>

Any help appreciated!

Thanks, M

0

There are 0 answers