Appending new XElement adds an entire XML to existing xml in stream

人盡茶涼 提交于 2019-12-12 00:36:08

问题


I have an existing XML stored in the InternalFielStorage as..

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>
  <Books>
        <Author name="Sam" />
  </Books>
</Root>

I am trying to append a "title" node under the "Author" node but the when saved, I am seeing a completly new xml added to the existing xml as..

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>
    <Books>
        <Author name="Sam" />
    </Books>
</Root>
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>  
    <Books>
        <Author name="Sam" />        
        <Title>Test</Title>
    </Books>
</Root>

Code I am using for this..

 using (IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication())
  {
     using (IsolatedStorageFileStream myStream = new IsolatedStorageFileStream(App.FileName, FileMode.Open, FileAccess.ReadWrite, myStore))
     {
           XDocument _xDoc = XDocument.Load(myStream);
           XElement srcTree = new XElement("Title", "test");
           _xDoc.Element("Root").Element("Books").Add(new XElement(srcTree));
           _xDoc.Save(myStream);

QUESTIONS:
1. How can I avoid the new XML from being appended to the existing one?
2. How can I make the "title" tag to be under the <"Author name="Sam"> tag?

Thanks in advance.


回答1:


When you load the stream, the position is set to the last byte of the file - you need to reset the position before saving the file.

Do this with

myStream.Position = 0;
_xDoc.Save(myStream);

See the documentation here



来源:https://stackoverflow.com/questions/19085366/appending-new-xelement-adds-an-entire-xml-to-existing-xml-in-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!