By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,660 Members | 1,109 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,660 IT Pros & Developers. It's quick & easy.

Problem using FileStream and XmlDocument

P: n/a
Hi.
I'm using a FileStream (instead of just the path to the xml file) to load an
XmlDocument. I'm doing this because I need to be able to prevent other
processes to update the file I'm working on. The problem is that I'm
getting multiple processing instructions and multiple root elements in my
xml file when I use a FileStream. Here is an example:

test_1.xml contains:
<?xml version="1.0" encoding="utf-8"?>
<root>
<myTag myValue="1">test</myTag>
</root>

test_2.xml contains:
<?xml version="1.0" encoding="utf-8"?>
<root>
<myTag myValue="2">test</myTag>
</root>

Public Sub test()
Dim fileStream As New FileStream("C:\Inetpub\wwwroot\test_1.xml",
FileMode.Open, FileAccess.ReadWrite, FileShare.None)
Dim xmlDocument As New XmlDocument()
Dim xmlDocument_2 As New XmlDocument()
Dim xmlNode As XmlNode
Dim xmlNodeNew As XmlNode

xmlDocument_2.Load("C:\Inetpub\wwwroot\test_2.xml" )
xmlNodeNew = xmlDocument_2.SelectSingleNode("root/myTag[@myValue='2']")

xmlDocument.Load(fileStream)

xmlNode = xmlDocument.ImportNode(xmlNodeNew.FirstChild, True)
xmlDocument.DocumentElement.AppendChild(xmlNode)
xmlDocument.Save(fileStream)

fileStream.Flush()
fileStream.Close()
End Sub

This is the result:
<?xml version="1.0" encoding="utf-8"?>
<root>
<myTag myValue="1">test</myTag>
</root>
<?xml version="1.0" encoding="utf-8"?>
<root>
<myTag myValue="1">test</myTag>test
</root>

Does anyone know what I'm doing wrong?

Thanks,
Shawn
Nov 12 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
"Shawn" <bo********@hotmail.com> wrote in message news:40******@news.wineasy.se...
processes to update the file I'm working on. The problem is that I'm
getting multiple processing instructions and multiple root elements in my
xml file when I use a FileStream.


It looks like you are using the same FileStream for input and output.
After XmlDocument has finished loading itself from the FileStream,
the "file position" of the FileStream is at the end of the file. Then
when you save the revised document, it appends it from this position
in the file creating what appears to be a duplicate.

Try using

fileStream.Seek( 0, SeekOrigin.Begin)

after loading the XmlDocument to re-set the "file position" to the start
of the file. Then the Save operation should overwrite the existing file
contents.
Derek Harmon
Nov 12 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.