我想根据某些条件将新的 XML 数据插入到现有的 XML 格式中。我有条件查询,但我发现要插入的示例似乎会引发错误“异常:对象引用未设置为对象的实例”。
这是我的 XML:-
<?xml version="1.0" encoding="UTF-8"?>
<myDataInfo
xmlns:fp="http://www.Myexample.com">
<myDataReport>
<startTime second="16" minute="51" hour="8" day="1" month="9" year="2016"/>
<myDataHub type="history" location="abc">
<myDataSet location="def">
<myData type="contact" id="9c1181ca-ffe7-46ae-9d37-fdefc05e59a0" batt="100" temp="24" name="Data2">
<evt val="open" time="86160"/>
<evt val="closed" time="86156"/>
</myData>
<myData type="motion" id="39ccc3d2-ab42-4f86-aa08-7f0eb665fece" batt="100" temp="24.3" name="Data3">
<evt val="active" time="86384"/>
<evt val="inactive" time="86380"/>
</myData>
</myDataSet>
</myDataHub>
</myDataReport>
我的查询得到:-
var eventResults1 = root.Descendants()
.Elements(ns + "myData")
.Where(el => (string)el.Attribute("name") == "def")
.Elements(ns + "evt")
.Select(el => new
{
t1 = el.Attribute("time").Value,
v1 = el.Attribute("val").Value
})
我要插入到mydata“Data2”中的数据
<evt val="closed" time="87000"></evt>
我试过
Elements(new XElement("evt", "time=90000,val=active"))
但是我没有成功插入。
感谢您的指点。
最佳答案
您需要获取符合您条件的 myData
元素:
var myData = root.Descendants(ns + "myData")
.Single(x => (string)x.Attribute("name") == "Data2");
然后添加一个新的子元素:
myData.Add(new XElement("evt",
new XAttribute("val", "closed"),
new XAttribute("time", "87000")
)
);
我建议 reading the documentation或一些教程,因为大部分内容都在里面。
关于c# - 使用 LINQ 将 XML 数据插入现有 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39327188/