0

I have an XML file with the format below

<ScriptElement>
      <ElementData xsi:type="FirstElement">
         .......
         .......
         .......
         <Description></Description>
         ........ 
      </ElementData>
</ScriptElement>
<ScriptElement>
      <ElementData xsi:type="SecondElement">
         .......
         .......
         .......
         <Description></Description>
         ........ 
      </ElementData>
</ScriptElement>
<ScriptElement>
      <ElementData xsi:type="ThirdElement">
         .......
         .......
         .......
         <Description></Description>
         ........ 
      </ElementData>
</ScriptElement>

I want to change the InnerText of the Description Node which is under the xsi:type="SecondElement"

When i try to get the attribute value of the namespace

string attrValist = Doc.SelectSingleNode("ScriptElements/ScriptElement/ElementData/@xsi:type").Value;

MessageBox.Show(attrValist);

Am getting an error as "Namespace Manager or XsIContext needed. The query has a prefix variable or user-defined function"

Could you please suggest me how should i move forward.

Thanks

Philemon philip Kunjumon
  • 1,417
  • 1
  • 15
  • 34

1 Answers1

1

Using Xml Linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication50
{
    class Program
    {
        const string FILENAME = @"c:\temp\test2.xml";
        static void Main(string[] args)
        {

            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, XElement> dict = doc.Descendants("ElementData").GroupBy(x => (string)x.Attributes().Where(y => y.Name.LocalName == "type").FirstOrDefault(), z => z)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

            XElement SecondElement = dict["SecondElement"];

            SecondElement.Element("Description").SetValue("abcd");
        }
    }


}
jdweng
  • 33,250
  • 2
  • 15
  • 20