Based on this SO solution, adding the same namespace to your child node will prevent creating empty xmlns=""
attributes. I'm not getting empty attributes, instead it duplicates the same xmlns in root to child node.
My current output:
<Root xmlns="http://my.namespace">
<FirstElement xmlns="http://my.namespace"/>
</Root>
Expected output:
<Root xmlns="http://my.namespace">
<FirstElement/>
</Root>
Sharing my code:
private XDocument CreateRootTag()
{
XNamespace xmlns = XNamespace.Get("http://my.namespace");
var xdec = new XDeclaration("1.0", "utf-8", "yes");
XDocument xml = new XDocument(
xdec,
new XElement(
xmlns "Root",
new XAttribute("version", "1.0"),
CreateFirstElementTag())); // <--- adding child node containing duplicate xmlns as root
return xml;
}
private XElement CreateFirstElementTag()
{
XNamespace xmlns = XNamespace.Get("http://my.namespace");
XElement firstElementTag = new XElement(xmlns "FirstElement","hello");
return firstElementTag;
}
How to prevent persisting xmlns="my.namespace"
attributes in child node?
Please let me know if you have any questions. Thanks.
CodePudding user response:
I ran your code as follows. And didn't encounter any issues.
c#
void Main()
{
XDocument xdoc = CreateRootTag();
Console.WriteLine(xdoc);
}
private XDocument CreateRootTag()
{
XNamespace xmlns = XNamespace.Get("http://my.namespace");
var xdec = new XDeclaration("1.0", "utf-8", "yes");
XDocument xml = new XDocument(
xdec,
new XElement(
xmlns "Root",
new XAttribute("version", "1.0"),
CreateFirstElementTag())); // <--- adding child node containing duplicate xmlns as root
return xml;
}
private XElement CreateFirstElementTag()
{
XNamespace xmlns = XNamespace.Get("http://my.namespace");
XElement firstElementTag = new XElement(xmlns "FirstElement", "hello");
return firstElementTag;
}
Output
<Root version="1.0" xmlns="http://my.namespace">
<FirstElement>hello</FirstElement>
</Root>