Link to home
Start Free TrialLog in
Avatar of CodeJunky
CodeJunkyFlag for United States of America

asked on

Write XML to file using XDocument

Hi all,
I have this code from Microsoft to create an xml file; but I can't find a way to write it to a file to my Windows Phone 8.1 project.

Dim sb As StringBuilder = New StringBuilder()
Dim xws As XmlWriterSettings = New XmlWriterSettings()
xws.OmitXmlDeclaration = True
xws.Indent = True

Using xw = XmlWriter.Create(sb, xws)
    Dim doc As XDocument = New XDocument(<Child><GrandChild>some content</GrandChild></Child>)
    doc.WriteTo(xw)
End Using

Console.WriteLine(sb.ToString())

Open in new window

Avatar of louisfr
louisfr

Pass a Stream to the XmlWriter.Create method instead of a StringBuilder.
Not sure FileStream is available on Windows Phone. I guess you can use an IsolatedStorageFileStream
Avatar of CodeJunky

ASKER

Nope that didn't work either.
I did manage to fix it though using a different technique....

Dim XMLDOC$ = txtSAFE_NAME.Text & ".xml"
        Dim sf As Windows.Storage.StorageFolder = RSCatalog_Loc
        Dim st As StorageFile = Await sf.CreateFileAsync(XMLDOC$)

        Dim xDoc As New XDocument(
            New XDeclaration("1.0", "utf-8", "yes") _
            , New XElement("RUSAFE" _
                , New XElement("INFOTBL",
                    New XElement("FILE_NAME", New XText(txtSAFE_NAME.Text.ToString())))))

st = Await sf.CreateFileAsync(XMLDOC$, CreationCollisionOption.OpenIfExists)
        Dim ws = TryCast(Await st.OpenStreamForWriteAsync(), Stream)
        xDoc.Save(ws)
 _

Open in new window


This does work; but the only issue i'm having wih it is that sometimes the data Is not saved.  I'm wondering if the Await function is causing a problem or perhaps I have to close the file. Strange, it works sometimes and not other..
ASKER CERTIFIED SOLUTION
Avatar of CodeJunky
CodeJunky
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I figured out a completely different way of solving the problem as all other solutions did not work.