Skip to content

Instantly share code, notes, and snippets.

@kirsbo
Created December 19, 2015 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirsbo/69b01c7bf00c777a329a to your computer and use it in GitHub Desktop.
Save kirsbo/69b01c7bf00c777a329a to your computer and use it in GitHub Desktop.
Saving XDocument to itself in VB.NET

Authored in 2010

While working with the LINQ XDocument object, I was attempting to modify the XML file loaded into the XDocument and then save it to itself. And while XDocument has a Save method, it needs a file path parameter. By default, XMLDocument would save to itself if no file path parameter was passed, but not so with XDocument.

Instead, you have to retrieve the file path of the loaded XML file using the BaseURI property of XDocument. The BaseURI property contains a URI (Uniform Resource Identifier), which essentially is a file path, to the "base", i.e. The loaded document. To save the XDocument to itself, you'd then think that all you need would be:

Dim xdoc As XDocument = XDocument.Load("C:\Test\Test.xml")
'Do manipulation
xdoc.Save(xdoc.BaseUri)

However, this doesn't work as the BaseUri property is empty! It turns out, than when loading an XML file into XDocument, you need to specify explicitly that the BaseURI should be set, by using a "LoadOptions" parameter. Like so:

Dim xdoc As XDocument = XDocument.Load("C:\Test\Test.xml", LoadOptions.SetBaseUri)
'Do manipulation
xdoc.Save(xdoc.BaseUri)

However, this doesn't work either. Now the BaseURI is not empty, but it's still not usable for the Save method. A URI is typically used for a path to a web resource, i.e. "www.xxx.net/index.htm". This means our BaseUri currently looks like this: "C:/Test/Test.xml" (notice the forward slashes). This format does not work with the Save method, because it expects a Windows file path, i.e. "C:\Test\Test.xml" with backslashes instead of forward slashes.

Thus we need to convert the BaseUri. We can do this by using the LocalPath property of a URI object. Unfortunately, the BaseUri object of the XDocument class is actually not a URI object - instead it's a string, so we cannot use xdoc.save(xdoc.BaseUri.LocalPath), though that would be the most intuitive way to go about it. Instead we'll have to create a URI object, load it with the XDocument's BaseUri property and then extract the localpath.

We do this by creating a string variable to hold the savepath. We initialize the string by setting it to the LocalPath property of a Uri object created inline, like so:

Dim xdoc As XDocument = XDocument.Load("C:\Test\Test.xml", LoadOptions.SetBaseUri)
Dim savePath As String = New Uri(xdocMenu.BaseUri).LocalPath
'Do manipulation
xdoc.Save(savePath)

While not a completely intuitive approach, the above code now properly saves the XDocument to itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment