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)

2
  • 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. Commented Jul 29, 2013 at 15:53
  • i have a xml file, where I have to change values on different positions. easy example: <command device="Tissue"id="10"></command> <command device="Tissue"id="20"></command> ... so I have to change numbering like id="0"id="1" and so on Commented Jul 29, 2013 at 16:08

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Why not use Descendants("command") instead of Descendants().Elements("command")?
(was long time away) what library I've to use? its not enough using.linq; XElement is not recognized.
used System.Xml.Linq; and became an issue: cannot convert ...XDocument to XElelent.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.