I am having XML, I want to add an attribute to all child node of xml document using C#
After review so many posts and blogs , confusing me
<root >
<EncrypteText >vishal sen</EncrypteText>
<Category >
<Categoryid >2</Categoryid>
<CategoryName >asdfasdfasdf</CategoryName>
</Category>
<CategoryArray >
<Categoryid >2</Categoryid>
<CategoryName >asdfasdfasdf</CategoryName>
</CategoryArray>
<CategoryArray >
<Categoryid >2</Categoryid>
<CategoryName >asdfasdfasdf</CategoryName>
</CategoryArray>
</root>
Convert like :
<root type="object">
<EncrypteText Type="object">vishal sen</EncrypteText>
<Category Type="object">
<Categoryid Type="object">2</Categoryid>
<CategoryName Type="object">asdfasdfasdf</CategoryName>
</Category>
<CategoryArray Type="object">
<Categoryid Type="object">2</Categoryid>
<CategoryName Type="object">asdfasdfasdf</CategoryName>
</CategoryArray>
<CategoryArray Type="object">
<Categoryid Type="object">2</Categoryid>
<CategoryName Type="object">asdfasdfasdf</CategoryName>
</CategoryArray>
</root>
I got this solutions
XmlDocument xml = new XmlDocument();
xml.Load(@"F:\XML\023615123651.xml");
XDocument document = XDocument.Load(new StringReader(xml.DocumentElement.OuterXml));
foreach (XElement node in document.Root.Descendants())
{
node.SetAttributeValue("Type", "object");
}
Based on your answer , I'd propose the following changes:
document.Root.Descendants()
to document.Descendants()
The following code shows the changes:
XDocument doc = XDocument.Load(@"F:\XML\023615123651.xml");
foreach(var el in doc.Descendants())
el.SetAttributeValue("Type", "object");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.