I have a xml file . I have to search for an attribute and to replace its value with some value using c#
Further i dont know how many times does this attribute come and in how many elements as this xml is generated dynamically.
Any help over this?
I have a xml file . I have to search for an attribute and
Share
One way is to load the document into a
System.Xml.XmlDocumentinstance, then find all occurrences of the respective attribute by using theSelectNodesmethod of theXmlDocumentinstance with an XPath expression and modify them accordingly.Here’s an example:
Assume the following Xml document:
Save the Xml document as
test.xml. In the same directory, compile the following program. It will change the values of all attributes that are calledmyAttribute(selected by the XPath expression//@myAttribute):(For your convenience, it also outputs the Xml document before and after the modification.)
With Namespaces
Now, the example is extended with namespaces (the XLink one, as requested by the OP):
Xml file:
C# code:
Remark 1: Note how only two occurrences of attributes called
myAttributeare modified now, the third one (in the<c>element) does not belong to the namespace indicated in the XPath expression.Remark 2: The namespace prefix used in the Xml file and the C# code happens to be the same (
xlink), but this is not required. You could, for example, usexlin the C# code instead and obtain the same result (only showing the changed lines):