I am using the following code
var xmlFile = fromConfiguration + @"xyz.xml";
XDocument document = XDocument.Load(xmlFile);
var xElement = document.Root;
xElement.Add(new XElement("elementName", "elementText"));
document.Save(xmlFile);
XDocument documentN = XDocument.Load(xmlFile);
XElement element = (from xml2 in documentN.Descendants("elementName")
select xml2).FirstOrDefault();
element.RemoveAttributes();
documentN.Save(xmlFile);
This gives me..
<elementName xmlns="">elementText</elementName>
xmlns is added by default. Is there any way I can add without xmlns?
<elementName>elementText</elementName>
This is what I need to parse in my xsl file.
ANy help ??
One of the ancestor elements must be setting a default namespace, e.g.
<foo xmlns="http://foo.bar">
<!-- Your element name -->
</foo>
If you want:
<foo xmlns="http://foo.bar">
<elementName>elementText</elementName>
</foo>
... then that means elementName
is implicitly in a namespace of http://foo.bar
, because the default is inherited. So you should use:
XNamespace ns = "http://foo.bar";
xElement.Add(new XElement(ns + "elementName", "elementText"));
If you might have different namespaces in different files, you could determine the default namespace programmatically - although it may not be the namespace of the root element, e.g.
<other:foo xmlns="http://foo.bar" xmlns:other="http://surprise">
<!-- This is still in http://foo.bar -->
<elementName>elementText</elementName>
</foo>
See more on this question at Stackoverflow