在文档节点之外插入包含名称空间的xml节点

时间:2016-06-23 20:02:57

标签: c# xml

我在C#中创建一个类似于以下

的XML文档
<?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">
<Document>
    <name>2015-05-17-track.kml</name>
</Document>
</kml>

我可以创建除kml节点之外的所有内容。如何将其添加到XmlDocument?

这是我正在使用的代码,没有kml节点。

doc = new XmlDocument();
XmlElement root = doc.CreateElement("Document");
doc.AppendChild(root);

//form the declaration
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null );
doc.InsertBefore(declaration, root);

XmlNode nameNode = doc.CreateNode(XmlNodeType.Element, "name", "");
nameNode.InnerText = name;
root.AppendChild(nameNode);

2 个答案:

答案 0 :(得分:0)

将子项附加到DocumentElement。

XmlNode nameNode = doc.CreateNode(XmlNodeType.Element, "name", "");
nameNode.InnerText = name;
doc.DocumentElement.AppendChild(nameNode );

答案 1 :(得分:0)

原来我被'Document'节点误导了。已经有一段时间了,我认为XmlDocument.DocumentElement总是有一个'Document'标签。错误! 这是修订后的代码

    doc = new XmlDocument();
    XmlElement root = doc.CreateElement( "kml" );
    root.SetAttribute( "xmlns", "http://www.opengis.net/kml/2.2" );
    root.SetAttribute( "xmlns:gx", "http://www.google.com/kml/ext/2.2" );
    root.SetAttribute( "xmlns:kml", "http://www.opengis.net/kml/2.2" );
    root.SetAttribute( "xmlns:atom", "http://www.w3.org/2005/Atom" );
    doc.AppendChild( root );

    //form the declaration
    XmlDeclaration declaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
    doc.InsertBefore( declaration, root );

    //Document node
    XmlElement documentNode = doc.CreateElement( "Document" );
    root.AppendChild( documentNode );

    //add the name node
    XmlNode nameNode = doc.CreateNode( XmlNodeType.Element, "name", "" );
    nameNode.InnerText = name;
    documentNode.AppendChild( nameNode );
相关问题