在IsolatedStorage中将元素添加到XML文件 [英] Add an element to an XML file in IsolatedStorage

查看:82
本文介绍了在IsolatedStorage中将元素添加到XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题.我尝试使用以下代码在XML中添加元素:

I have a little problem. I try to add an element in XML with this code:

using (IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!myStore.FileExists("categorie_settings.xml"))
                {
                    using (IsolatedStorageFileStream myStream = new IsolatedStorageFileStream("categorie_settings.xml", FileMode.Create, myStore))
                    {
                        XNamespace _name = "";
                        XDocument new_doc = new XDocument(
                                new XDeclaration("1.0", "utf-8", ""),
                                new XElement(_name + "Root",
                                    new XElement("Row",
                                        new XElement("Nome", query.FirstOrDefault().Nome.ToString()),
                                        new XElement("Tipo", query.FirstOrDefault().Tipo.ToString()),
                                        new XElement("URL", query.FirstOrDefault().URL.ToString()),
                                        new XElement("Err", "Errore1")
                                        )));


                        new_doc.Save(myStream);

                    }
                }
                else
                {

                    using (IsolatedStorageFileStream myStream = new IsolatedStorageFileStream("categorie_settings.xml", FileMode.Open, myStore))
                    {
                        XDocument doc1 = XDocument.Load(myStream);
                        doc1.Element("Root").Add(
                            new XElement("Row",
                                new XElement("Nome", query.FirstOrDefault().Nome.ToString()),
                                new XElement("Tipo", query.FirstOrDefault().Tipo.ToString()),
                                new XElement("URL", query.FirstOrDefault().URL.ToString()),
                                new XElement("Err", "Errore2")));


                        doc1.Save(myStream);




                    }



                }

在第二次使用中,我想向XML文件添加一个项目,但是2次调用后的结果是这样:

In the second Using I want to add an item to the XML file but the result after 2 call is this:

    <?xml version="1.0" encoding="utf-8"?>
<Root>
  <Row>
    <Nome>Homepage</Nome>
    <Tipo>News</Tipo>
    <URL>/web/ansait_web_rss_homepage.xml</URL>
    <Err>Errore1</Err>
  </Row>
</Root><?xml version="1.0" encoding="utf-8"?>
<Root>
  <Row>
    <Nome>Homepage</Nome>
    <Tipo>News</Tipo>
    <URL>/web/ansait_web_rss_homepage.xml</URL>
    <Err>Errore1</Err>
  </Row>
  <Row>
    <Nome>Cronache</Nome>
    <Tipo>News</Tipo>
    <URL>/web/notizie/rubriche/cronaca/cronaca_rss.xml</URL>
    <Err>Errore2</Err>
  </Row>
</Root>

似乎在整个文件加上新元素之前将其添加到文件中.我该如何添加元素?

It seems that adds to the file before the entire file plus the new element. How can I make just add the element?

推荐答案

错误开始的道歉(已删除).这是您的示例中的第二个使用语句的摘要.注意我们如何选择第一个Row元素(firstRow),然后选择AddBeforeSelf.假设您希望新元素位于列表顶部.

Apologies for the false start (deleted). Here's a snippet that would go into the second using-statement in your example. Note how we select the first Row element (firstRow) and then AddBeforeSelf. This assumes you want the new element at the top of the list.

// See update, below, for corrected version

XDocument doc1 = XDocument.Load( myStream );
var root = doc1.Element( "Root" );
var rows = root.Descendants( "Row" );
var firstRow = rows.First();
firstRow.AddBeforeSelf(
      new XElement( "Row",
          new XElement( "Nome", "Homepage2" ),
          new XElement( "Tipo", "News2" ),
          new XElement( "URL", "/web/xml2" ),
          new XElement( "Err", "Errore2" ) ) );
doc1.Save( myStream );

已更新:正如OP在评论中指出的那样,他希望添加新元素,而不是添加新元素.此外,他在随后的调用中也获得了例外.该异常是由于XDocument.Save(Stream stream)追加到流中,因此您最终在文件中找到了两个XML文档(格式不正确的XML).以下内容解决了这两个问题.

Updated: as the OP points out in the comments, he wanted the new element appended, not prepended. Additionally he gets an exception on subsequent invocations. That exception is due to XDocument.Save( Stream stream ) appending to the stream, so you wind up with two XML documents in the file (not well-formed XML). This following addresses both of those issues.

XDocument doc1;
using (IsolatedStorageFileStream myStream = new IsolatedStorageFileStream( "categorie_settings.xml", FileMode.Open, myStore ))
{
    doc1 = XDocument.Load( myStream );
}

var root = doc1.Element( "Root" );
var rows = root.Descendants( "Row" );
var lastRow = rows.Last();
lastRow.AddAfterSelf(
      new XElement( "Row",
          new XElement( "Nome", "Homepage2" ),
          new XElement( "Tipo", "News2" ),
          new XElement( "URL", "/web/xml2" ),
          new XElement( "Err", "Errore2" ) ) );

using (IsolatedStorageFileStream myStream = new IsolatedStorageFileStream( "categorie_settings.xml", FileMode.Create, myStore ))
{  
  doc1.Save( myStream );
}

在创建文件的流上完成保存,从而覆盖先前的文件.或者,您可以使用XDocument.Save(String filename)来替换文件的内容.

There the save is done on a stream that creates the file, thereby overwriting the previous file. Alternatively you could use XDocument.Save( String filename ) which does replace the contents of the file.

这篇关于在IsolatedStorage中将元素添加到XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆