I have a xml file which starts like this:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2"
xmlns:kml="http://www.opengis.net/kml/2.2"
xmlns:atom="http://www.w3.org/2005/Atom">
When I run my below code it it gives me error 'xsi' is an undeclared prefix.
var xDoc = XDocument.Load(kmlFileUrl); //throws error xsi' is an undeclared prefix
XNamespace ns = "http://www.opengis.net/kml/2.2";
xDoc.Root
.Elements(ns + "Document")
.Elements(ns + "Placemark")
.GroupBy(i => (string)i)
.SelectMany(g => g.Skip(1))
.Remove();
I researched on internet and found that this occurs due to missing of the xsi namespace declaration. I tried with this code
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
XDocument doc = new XDocument(
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance")
);
Expected result:
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2"
xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
Since I am not able to load the file how do I add the namespace to the existing file node such that I do not have to change my other code lines?
Edit
The difference is the solution there has this line
XmlReader rd = XmlReader.Create(new StringReader(strXmlFile), xset, context);
Here the StringReader taken input as string and I am using a xml file. The xml files is too long and I do not want to write extra code to first convert it in string and than do other stuff. Also please note that I am already using the XDocument xDoc variable in code to find the elements.
I was expecting someone to advise on how can I use the XDocument and also add the namespace. Hope this makes sense.
Let me know if someone wants to help and needs more inputs on this.