gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 01:42:42 25 4
gpt4 key购买 nike

我需要能够在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com