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

本文关键字:节点 空间 包含名 xml 插入 文档 | 更新日期: 2023-09-27 17:49:14

我正在用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);

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

为DocumentElement添加子元素。

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

原来我被" 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 );