c# - 如何创建带前缀的 XmlElement 属性?

标签 c# xml

我需要能够在 xml 元素中定义带有前缀的属性。

例如...

<nc:Person s:id="ID_Person_01"></nc:Person>

为了做到这一点,我认为以下方法会奏效。

XmlElement TempElement = XmlDocToRef.CreateElement("nc:Person", "http://niem.gov/niem/niem-core/2.0");
TempElement.SetAttribute("s:id", "http://niem.gov/niem/structures/2.0", "ID_Person_01");

不幸的是,XmlElement.SetAttribute(string, string, string) 似乎不支持解析前缀,因为我收到以下错误。

The ':' character, hexadecimal value 0x3A, cannot be included in a name.

如何定义带前缀的属性?

最佳答案

如果您已经在根节点中声明了您的命名空间,您只需更改 SetAttribute 调用以使用无前缀的属性名称。因此,如果您的根节点定义了这样的命名空间:

<People xmlns:s='http://niem.gov/niem/structures/2.0'>

您可以这样做,属性将选取您已经建立的前缀:

// no prefix on the first argument - it will be rendered as
// s:id='ID_Person_01'
TempElement.SetAttribute("id", "http://niem.gov/niem/structures/2.0", "ID_Person_01");

如果您尚未声明命名空间(及其前缀),则三字符串 XmlDocument.CreateAttribute overload 会为你做这件事:

// Adds the declaration to your root node
var attribute = xmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0");
attribute.InnerText = "ID_Person_01"
TempElement.SetAttributeNode(attribute);

关于c# - 如何创建带前缀的 XmlElement 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2255311/

相关文章:

c# - GetDirectoryEntry 不返回所有属性

python - 操作格式良好的 xml(在 linux 下运行的任何语言)

c# - 如何确保泛型的不变性

xml - 如何在 Maven 中设置属性标志时跳过下载依赖项

java - XmlJavaTypeAdapter XmlElement 不适用于多个字段

java - Recyclerview 的卡片布局始终大小相同

xml - 节点名称中包含特殊字符的 Groovy XmlSlurper

c# - Bot Framework : Enable PromptDialog. Cortana 说出的文本

c# - 关系数据库的全文搜索?

c# - OPC UA-.NETStandardLibrary : the simplest way to access historical data