Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading an XML document with Linq

Tags:

c#

.net

xml

linq

I would like to read an XML document using the following code:

XDocument xdoc = XDocument.Load(fileName);

This does not work, and the following exception is thrown (freely translated by me):

System.Xml.XmlException: 'xlink' is a non declared prefix.

Here is the XML line the exception refers to:

<use xlink:href="#lend13" transform="scale(-8.5,-8.5) "/>

How can I modify the loading code, so that the XML document will be read successfully? Do I have to set up namespaces beforehand? How?

like image 737
Boris Avatar asked Jul 02 '15 11:07

Boris


People also ask

Does LINQ work with XML?

The most important advantage of LINQ to XML is its integration with Language-Integrated Query (LINQ). This integration enables you to write queries on the in-memory XML document to retrieve collections of elements and attributes.

Which of the following option is created to retrieve data into XML using LINQ?

The LINQ to XML will bring the XML document into memory and allows us to write LINQ Queries on in-memory XML document to get the XML document elements and attributes. To use LINQ to XML functionality in our applications, we need to add "System. Xml. Linq" namespace reference.

What is the difference between XDocument and XmlDocument?

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument .


2 Answers

I think this will be helpful it worked for me...

http://aspnetgotyou.blogspot.com/2010/06/xdocument-or-xelement-with-xmlnamespace.html

like image 103
Saveendra Ekanayake Avatar answered Oct 11 '22 03:10

Saveendra Ekanayake


if you can edit the Xml, you can fix by defining the namespace for it

<use xlink:href="#lend13" transform="scale(-8.5,-8.5) 
xmlns:xlink="http://myurl.com/" />

otherwise you can predefine the namespace when using XmlDocument

XmlDocument.DocumentElement.SetAttribute("xmlns:xlink", "http://myurl.com/");

and in linq to XML you can define the attribute using XNamesace

XNamespace ns = "http://myurl.com/";
like image 26
n00b Avatar answered Oct 11 '22 03:10

n00b