c# - 使用指定的电子表格类型创建 XmlNode

标签 c# xml xpath namespaces xmlnode

我在 xml 操作方面有点新。我想创建一个 XmlNode。

我已经尝试过 OwnerDocument.CreateElement 方法,也尝试过 OwnerDocument.CreateNode 方法,但我无法创建以下 XmlNode:

<Data ss:Type="String"/>

你能帮我解决这个问题吗?我已经尝试了我发现的所有东西,但什么也没有。

最佳答案

XmlDocument已在 .NET 框架中被更新的 XDocument 取代API,它与 Linq 配合得更好,通常是用于 XML 操作的现代库。

下面是一个示例,您可以使用该 API 将元素插入到现有 XML 文档中,该文档的属性具有先前声明的命名空间前缀。

XDocument ownerDocument = XDocument.Parse("<OwnerDocument></OwnerDocument>");
XNamespace ssNameSpace = "http://whatever/somenamespace";

// add namespace declaration to the root, set ss as the namespace prefix
// you only need to do this if the document doesn't already have the namespace declaration
ownerDocument.Root.Add(new XAttribute(XNamespace.Xmlns + "ss", ssNameSpace.NamespaceName));

// add our new data element to the root, and add the type attribute prefixed with the ss namespace
ownerDocument.Root.Add(new XElement("Data", new XAttribute(ssNameSpace + "Type", "String")));

这将产生以下 XML:
<OwnerDocument xmlns:ss="http://whatever/somenamespace">
    <Data ss:Type="String" />
</OwnerDocument>

如果您真的很想使用 XmlDocument ,您可以在那里实现相同的效果,如下所示:
XmlDocument ownerDocument = new XmlDocument();
ownerDocument.LoadXml("<OwnerDocument></OwnerDocument>");

// add namespace declaration to the root, set ss as the namespace prefix
var nsDeclarationAttribute = ownerDocument.CreateAttribute("xmlns:ss");
nsDeclarationAttribute.Value = "http://whatever/somenamespace";
ownerDocument.DocumentElement.Attributes.Append(nsDeclarationAttribute);

// add data element, and add a type attribute to that
var dataElement = ownerDocument.CreateElement("Data");
var typeAttribute = ownerDocument.CreateAttribute("Type", "http://whatever/somenamespace");
typeAttribute.Value = "String";            
dataElement.Attributes.Append(typeAttribute);

// append to main document
ownerDocument.DocumentElement.AppendChild(dataElement);

关于c# - 使用指定的电子表格类型创建 XmlNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57115285/

相关文章:

c# - NHibernate Criteria - 如何正确使用 group by 语句?

xml - 甲骨文 XPath : Selecting first occurrence of an element

html - 使用 XSLT 将 XML 转换为 HTML

xml - XSLT-选择以下项目直到特定标签

python - 解析具有未定义实体的 XHTML5

XML 文档中带有命名空间的 Javascript XPath

c# - 我可以运行应用程序(或存储过程)并从触发器获取结果吗

c# - 使用java程序控制网络浏览器

c# - Queryable.Any() 返回 null?

xml - 在 golang 中解码到实例化的空接口(interface)