【问题标题】:Adding XElement to XML file using Linq to XML使用 Linq to XML 将 XElement 添加到 XML 文件
【发布时间】:2012-08-15 03:57:02
【问题描述】:

使用 Linq to XML,我正在尝试将 XElement 添加到现有 XML 文件中。 它必须在 Windows Phone .NET 框架中完成。 目前我的 XML 文件如下所示:

    <?xml version="1.0" encoding="utf-8"?>
    <Kids>
      <Child>
        <Name>Kid1</Name>
        <FirstName>hisname</FirstName>
      </Child>
    </Kids>

and my code looks like this:



    using (IsolatedStorageFileStream stream = 
               new IsolatedStorageFileStream("YourKids.xml", fileMode, store))
    { 
        XDocument x = XDocument.Load(stream);
        XElement t =  new XElement("Child",
                                           new XElement("Name", pName),
                                           new XElement("FirstName", pFirstname));

       t.Add(from el in x.Elements()
             where el == el.Descendants("Child").Last()
             select el);

       x.Save(stream);
    }

this doesn't do what I want to achieve. I want to add a new "Child" element to the the exisiting XML file like this :

     <?xml version="1.0" encoding="utf-8"?>
    <Kids>
      <Child>
        <Name>Kid1</Name>
        <FirstName>hisname</FirstName>
      </Child>
    <Child>
        <Name>kid2</Name>
        <FirstName>SomeName</FirstName>
      </Child>
    </Kids>

Could use some help because I am stuck ;-)

After the tips from GSerjo, my code looks like this now:

 try
            {

                if (store.FileExists("YourKids.xml"))
                {



                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("YourKids.xml",FileMode.Open, store))
                    {


                        var x = XElement.Load(stream);
                        var t =  new XElement("Child",
                                                        new XElement("Name", pName),
                                                        new XElement("FirstName", pFirstname)
                                                                  );

                        x.Add(t);

                        x.Save(stream);




                        stream.Close();
                        return;
                    }

                }
                else
                {



                    using (IsolatedStorageFileStream CreateIsf = new IsolatedStorageFileStream("YourKids.xml",FileMode.Create,store))
                    {

                        var xDoc = new XElement("Kids",
                                                     new XElement("Child",
                                                       new XElement("Name", pName),
                                                       new XElement("FirstName", pFirstname)
                                                                 )

                                                  );

                        xDoc.Save(CreateIsf);
                        CreateIsf.Close();

                        return;
                    }
                }
            }
            catch (Exception ex)
            {
              message = ex.Message;
            }

这给了我一个这样的 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<Kids>
  <Child>
    <Name>test</Name>
    <FirstName>test</FirstName>
  </Child>
</Kids><?xml version="1.0" encoding="utf-8"?>
<Kids>
  <Child>
    <Name>test</Name>
    <FirstName>test</FirstName>
  </Child>
  <Child>
    <Name>testing</Name>
    <FirstName>testing</FirstName>
  </Child>
</Kids>

这仍然不正确,有什么想法吗?

【问题讨论】:

    标签: windows silverlight windows-phone-7 xelement


    【解决方案1】:

    初始xml文件

    <?xml version="1.0" encoding="utf-8"?>
    <Kids>
      <Child>
        <Name>Kid1</Name>
        <FirstName>hisname</FirstName>
      </Child>
    </Kids>
    

    以下代码向现有 xml 添加一个新子项

        [Test]
        public void Test()
        {
            string filPath = @"YourKids.xml";
            var root = XElement.Load(filPath);
             var newChild =  new XElement("Child",
                                       new XElement("Name", "NewName"),
                                       new XElement("FirstName", "NewFirstName"));
             root.Add(newChild);
            root.Save(filPath);
        }
    

    结果 xml 文件

    <?xml version="1.0" encoding="utf-8"?>
    <Kids>
      <Child>
        <Name>Kid1</Name>
        <FirstName>hisname</FirstName>
      </Child>
      <Child>
        <Name>NewName</Name>
        <FirstName>NewFirstName</FirstName>
      </Child>
    </Kids>
    

    更新

    保存时的错误,您应该将流长度设置为 0

    解释

    读取现有文件后,不会删除任何数据

    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("YourKids.xml",FileMode.Open, store))
                        {
                            var x = XElement.Load(stream);
    

    所以当你调用的时候,数据已经被追加了

       x.Save(stream);
       stream.Close();
    

    x.Save(stream);之前添加stream.SetLength(0);,所有数据都会被覆盖。

    这里是完整版

                if (store.FileExists("YourKids.xml"))
                {
                    using (var stream = new IsolatedStorageFileStream("YourKids.xml", FileMode.Open,
                                                                                         store))
                    {
                        var x = XElement.Load(stream);
                        var t = new XElement("Child",
                                             new XElement("Name", pName),
                                             new XElement("FirstName", pFirstname)
                            );
                        x.Add(t);
                        stream.SetLength(0);
                        x.Save(stream);
                        stream.Close();
                    }
                }
                else
                {
                    using (var CreateIsf = new IsolatedStorageFileStream("YourKids.xml", FileMode.Create, store))
                    {
                        var xDoc = new XElement("Kids",
                                                new XElement("Child",
                                                             new XElement("Name", pName),
                                                             new XElement("FirstName", pFirstname)
                                                    )
                            );
                        xDoc.Save(CreateIsf);
                        CreateIsf.Close();
                    }
                }
    

    请注意:我已将 return 语句删除为无用。

    附:看看resharper,它可以改进代码。

    【讨论】:

    • 哇,谢谢您的快速回复。尽管它将新的子元素添加到我的 XML 文件中,但奇怪的是它保留了我的初始 xml 文件并将结果 xml 文件添加到我的初始文件下,使 xml 文件看起来像: Kid1hisnameKid1他的名字NewNameNewFirstName儿童> 儿童>
    • 看起来你的保存结果不正确,root.Save(filPath) - 替换现有文件。你能显示你最后的代码吗
    • 我已经用完整的代码编辑了我的第一篇文章,所以你可以看到我是如何保存我的 xml 文件的。
    • 谢谢 GSerjo,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多