简体   繁体   中英

Adding an attribute to xml document child node using linq

I'm trying to create an element and defining the path to the xml document, one of my tries was:

XElement main = XElement.Load(xmlpath);

Then i tried to select the existing element that I want to add an attribute

main.XPathSelectElement("/Row/ip_addresses").SetAttributeValue("id", sp_range.ToString()); 

Las tried these both

main.XPathSelectElement("/Row/ip_addresses").ReplaceAttributes("id", sp_range.ToString());

There is no errors presented in this code just nothing happens to the xml document and the existing Element, the existing child element is and the Parent is I am using Xpath to navigate to the child element that I want to add attribute to that don't exist according to Linq we are supposed to be able to change attributes that exist or don't exist and change ElementTags that exist or create Elements that don't exist.

Please any advise would help

You don't appear to be persisting/saving the changes...

Try the XElement.Save method

You are selecting from "Row" which doesn't exist under the current element. Current element itself is the "Row". As such, you need to select from the root "/ip_addresses" , not from "/Row/ip_addresses" .

main.XPathSelectElement("/ip_addresses").SetAttributeValue("id",sp_range.ToString()));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM