How to parse an xml fragment in nodes and add them to a node with the specified default namespace so that they are part of this namespace?

I have the following input

<row test="1" />

and want to generate the following output when using XmlTextWriter.

<?xml version="1.0"?>
<root xmlns="urn:default">
  <row test="1" />
</root>

According to the documentation for InnerXml ( MSDN ), the following code should work correctly.

var outputdoc = new XmlDocument();
outputdoc.AppendChild(outputdoc.CreateXmlDeclaration("1.0", string.Empty, string.Empty));
outputdoc.AppendChild(outputdoc.CreateElement("root", "urn:default"));
outputdoc.DocumentElement.InnerXml = "<row test=\"1\" />";

var writer = new XmlTextWriter(filename, Encoding.UTF8) { Formatting = Formatting.Indented, Indentation = 1 };
outputdoc.WriteTo(writer);
writer.Close();

Instead, I get the following output:

<?xml version="1.0"?>
<root xmlns="urn:default">
  <row test="1" xmlns="" />
</root>

What do I need to do?

EDIT:

I did not make the possible input clear enough. It was supposed to be a piece of Xml, so it could be one element, more than one element with any number of children anyway. For instance:

<row test="1" />

or

<row test="1" />
<row test="2" />

or

<row><test>1</test></row>

or

<row><test>1</test></row>
<row test="2" />
+3
source share
3 answers

System.Xml? XElement, :

XElement root = new XElement(XName.Get("root", "urn:default"));
XElement child = XElement.Parse("<row test=\"1\" />");
root.Add(child);
child.Name = XName.Get("row", "urn:default");
Console.WriteLine(root.ToString());

:

<root xmlns="urn:default">
    <row test="1" />
</root>
+2

XmlTextWriter, , , , , .

using(var writer = new XmlTextWriter(filename, Encoding.UTF8) { Formatting = Formatting.Indented, Indentation = 1 }) {
    writer.WriteStartDocument();
    writer.WriteStartElement("row","urn:default");
    writer.WriteRaw("<row test=\"1\" />");
    writer.WriteEndElement();
    writer.WriteEndDocument();
}
+1

, XML : -, API, , InnerXML...

<row test="2"/> 

, ? XPath, .

. , reset xmlns="".

InnerXML?

outputdoc.DocumentElement.InnerXml = "<row test=\"1\" xmlns=\"urn:default\" />"; 

: @somori, http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.innerxml.aspx

node . .

Microsoft (DOM).

DOM ...

+1

Source: https://habr.com/ru/post/1764519/


All Articles