使用LINQ将XML数据插入到现有的XML中

本文关键字:XML 插入 LINQ 数据 使用 | 更新日期: 2023-09-27 18:05:36

我想根据某些条件将新的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"))

但是我没有成功插入。

使用LINQ将XML数据插入到现有的XML中

您需要获得符合您的标准的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")
    )
);

我建议阅读文档或一些教程,因为大多数这些东西都在那里。

我觉得你把事情弄得比实际困难多了。
只要知道Elements("...")将只返回直接子元素(只向下一层),而Descendants("...")将返回每个子元素,无论嵌套有多深。所以这里不用Elements(),只用Descendants()

var myDataElement =
    // Find all elements with the name "MyData"
    root.Descendants("myData")
    //Filter out the one that has the attribute you're looking for
    .Single(element => element.Attribute("name").Value == "Data2");
//Add the new element
myDataElement.Add(
    new XElement("evt",
        new XAttribute("val", "closed"),
        new XAttribute("time", "87000")
    )
);

尝试以下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:'temp'test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement addElement = doc.Descendants("myData").Where(x => x.Elements("evt").Where(y => (string)y.Attribute("val") == "open").Count() == 0).FirstOrDefault();
            if (addElement != null)
            {
                addElement.Add( new XElement("evt", new object[] {
                    new XAttribute("val","closed"),
                    new XAttribute("time","87000")
                }));
            }
        }
    }
}