0

I'm using C# with .net 3.5 and have a few cases where I want to replace some substrings in the XML attributes of an XmlDocument with something else.

One case is to replace the single quote character with ' and the other is to clean up some files that contain valid XML but the attributes' values are no longer appropriate (say replace anything attribute which starts with "myMachine" with "newMachine").

Is there a simple way to do this, or do I need to go through each attribute of every node (recursively)?

2
  • By "badly created", do you mean the documents aren't well-formed XML? Commented Jul 26, 2011 at 21:10
  • No I mean some of the attribute were set to wrong values (for example, many attributes point to a shared folder on a machine which no longer exists) Commented Jul 26, 2011 at 21:12

2 Answers 2

2

One way to approach it is to select a list of the correct elements using Linq to XML, and then iterate over that list. Here's an example one-liner:

 XDocument doc = XDocument.Load(path);
 doc.XPathSelectElements("//element[@attribute-name = 'myMachine']").ToList().ForEach(x => x.SetAttributeValue("attribute-name", "newMachine"));

You could also do a more traditional iteration.

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

Comments

0

I suggest taking a look at LINQ to XML. There's a collection of code snippets that can help you get started here - LINQ To XML Tutorials with Examples

LINQ to XML should allow you to do what you're looking to do, and you'll probably find it easy once you've played with it a bit.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.