I’m encountering an issue with using LINQ to manipulate XML. To demonstrate, I created a simple test with two XML files. The problem arises after I add a node; altering its information doesn’t change the added node. However, if I add this node along with its parent node, it does change. I’m puzzled because I didn’t create a new instance at all. Any assistance would be appreciated.
test2.xml
<?xml version="1.0" encoding="utf-8"?>
<haha>
</haha>
test1.xml
<?xml version="1.0" encoding="utf-8"?>
<root id="100">
<node id="1" name="a"/>
<node id="2" name="b"/>
<node id="3" name="c"/>
</root>
code
XElement x1 = new XElement(XElement.Load("D:\test1.xml"));
XElement x2 = new XElement(XElement.Load("D:\test2.xml"));
XElement node1=x1.Element("node");
x2.Add(node1);
x2.Add(x1);
node1.Attribute("id").Value = "33";
result x2
<haha>
<node id="1" name="a" />
<root id="100">
<node id="33" name="a" />
<node id="2" name="b" />
<node id="3" name="c" />
</root>
</haha>
New contributor
苏景冬 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.