Search code examples
c#xmlxmldocumentxmlreader

Replace attribute value in XML (attrubute path variable)


I'm working with an XML document that contains a structure that looks similar to this:

<SW.Blocks.OB ID="$">
<AttributeList>
<ObjectList>
  <MultilingualText ID="$" CompositionName="Comment">
    <ObjectList>
      <MultilingualTextItem ID="$" CompositionName="Items">
        <AttributeList>
          <Culture>en-US</Culture>
          <Text />
        </AttributeList>
      </MultilingualTextItem>
      <MultilingualTextItem ID="$" CompositionName="Items">
        <AttributeList>
          <Culture>nl-NL</Culture>
          <Text />
        </AttributeList>
      </MultilingualTextItem>
      <MultilingualTextItem ID="$" CompositionName="Items">
        <AttributeList>
          <Culture>de-DE</Culture>
          <Text />
        </AttributeList>
      </MultilingualTextItem>
    </ObjectList>
  </MultilingualText>
</ObjectList>
</SW.Blocks.OB>

I'm searching for the attribute ID. This attribute can occur everywhere. I already can find the value of those ID's

        XmlTextReader reader = new XmlTextReader(@"Main.xml");
        while (reader.Read())
        {
            reader.MoveToContent();
            string test = reader.GetAttribute("ID");

            if (test == "$")
            {
             MessageBox.Show(test);
            } 
        }

But I can't change them. Goal: Find ID, no matter where, and replace the value of that attibute with a 'value'.

Who could help me out? I already tried Xdocument and Xmldocument as well. I can't figure it out.


Solution

  • Using xml linq

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    
    namespace ConsoleApplication13
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
    
                List<XElement> ids = doc.Descendants().Where(x => x.Attribute("ID") != null).ToList();
    
                int indNo = 1;
                foreach (XElement id in ids)
                {
                    id.Attribute("ID").SetValue(indNo++);
                }
    
    
    
            }
    
    
        }
    
    }