我在 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/