1

how I can change the attribute "id" using my source code?

static void Main(string[] args)
    {

        XmlTextReader reader = new XmlTextReader(@"C:\Users\1.xml");
        XmlNodeList elementList = reader.
        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element: // The node is an element
                    {
                        reader.ReadToFollowing("command"); 
                        reader.MoveToAttribute("id");                         
                        Console.Write(reader.Value);
                        Console.WriteLine(" ");                    
                    }
                    break;
            }
        }           
        Console.Read();
    }

I saw some examples, but they have used another methods that don't work with mine. (I'm a noobie)

Evgeny Bubnov
  • 77
  • 1
  • 6
  • You're just using XmlReader - that's for reading, not changing. You'd be better off using LINQ to XML, but we can't tell really what you're trying to do at the moment. – Jon Skeet Jul 29 '13 at 15:53
  • i have a xml file, where I have to change values on different positions. easy example: ... so I have to change numbering like id="0"id="1" and so on – Evgeny Bubnov Jul 29 '13 at 16:08

2 Answers2

1

I would use LINQ to XML

XElement doc=XDocument.Load(path);
foreach(var element in doc.Descendants().Elements("command"))
{
element.Attribute("id").Value=yourValue;
}
doc.Save(path);

This would change each command element's id attribute

Aki la
  • 351
  • 3
  • 17
Anirudha
  • 32,393
  • 7
  • 68
  • 89
0

Code above didn't fly for me

this works thought

var doc = XDocument.Load(path);
    foreach(var element in doc.Descendants("command"))
    {
        element.Attribute("id").Value = id;
    }

doc.Save(path);

Hope this saves you some time.

Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265