C# 操作xml 在指定节点插入新节点,该如何操作?
C#操作xml在指定节点插入新节点,该如何操作?<?xmlversion="1.0"standalone="yes"?><DocumentElement><MM02id=...
C# 操作xml 在指定节点插入新节点,该如何操作?
<?xml version="1.0" standalone="yes"?><DocumentElement> <MM02 id="1"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD12033SUB7</FVAL> </MM02> <MM02 id="2"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD10001SUB9</FVAL> </MM02> <MM02 id="3"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD10001SUB10</FVAL> </MM02></DocumentElement>
实现后是:
<?xml version="1.0" standalone="yes"?><DocumentElement> <MM02 id="1"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD12033SUB7</FVAL> </MM02>
<MM02 id="1"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD12033SUB7</FVAL> </MM02> <MM02 id="2"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD10001SUB9</FVAL> </MM02> <MM02 id="3"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD10001SUB10</FVAL> </MM02></DocumentElement> 展开
<?xml version="1.0" standalone="yes"?><DocumentElement> <MM02 id="1"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD12033SUB7</FVAL> </MM02> <MM02 id="2"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD10001SUB9</FVAL> </MM02> <MM02 id="3"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD10001SUB10</FVAL> </MM02></DocumentElement>
实现后是:
<?xml version="1.0" standalone="yes"?><DocumentElement> <MM02 id="1"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD12033SUB7</FVAL> </MM02>
<MM02 id="1"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD12033SUB7</FVAL> </MM02> <MM02 id="2"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD10001SUB9</FVAL> </MM02> <MM02 id="3"> <FNAM>BDC_SUBSCR</FNAM> <FVAL>SAPLMGD10001SUB10</FVAL> </MM02></DocumentElement> 展开
展开全部
首先获取想要复制节点的值,然后添加。
XElement rootNode = XElement.Load("test.xml");
var result = from m in rootNode.Elements ("MM02")
where m.Attribute ("id").Value =="1"
select new
{
id=m.Attribute ("id").Value ,
fname = m.Element ("FNAM").Value ,
fval = m.Element("FVAL").Value
};
foreach (var s in result)
{
XElement x =
new XElement("MM02", new XAttribute("id",s.id ),
new XElement ("FNAM",s.fname ),
new XElement ("FVAL",s.fval)
);
XElement node = rootNode.Element("MM02");
rootNode.Element("MM02").AddAfterSelf(x);
rootNode.Save("test.xml");
}
追问
你好,我用你的来实现,结果是多了一行及复制了两行,希望您在帮忙修改下,谢谢
追答
这个问题是这样的,在操作集合时不应该直接对集合进行修改,应该操作临时变量,修改后代码为
XElement rootNode = XElement.Load("test.xml");
XElement temp = XElement.Load("test.xml");
var result = from m in temp.Elements("MM02")
where m.Attribute ("id").Value =="1"
select new
{
id=m.Attribute ("id").Value ,
fname = m.Element ("FNAM").Value ,
fval = m.Element("FVAL").Value
};
foreach (var s in result)
{
XElement x =
new XElement("MM02", new XAttribute("id", s.id),
new XElement("FNAM", s.fname),
new XElement("FVAL", s.fval)
);
XElement node = rootNode.Element("MM02");
rootNode.Element("MM02").AddAfterSelf(x);
}
rootNode.Save("test.xml");
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询