如何在C#的XML节点中设置json:Type="Decimal"属性
解决XML节点添加带命名空间前缀属性的问题
你遇到的问题核心是:仅设置属性前缀但未绑定对应的命名空间URI,XML解析器会认为该前缀无效,最终输出时自动忽略前缀。
正确实现步骤
要生成带json:Type前缀的属性,必须先为json前缀绑定命名空间(Json.NET默认使用的命名空间是http://james.newtonking.com/projects/json),再创建关联该命名空间的属性。
完整代码示例
// 定义Json.NET使用的json命名空间URI string jsonNamespace = "http://james.newtonking.com/projects/json"; XmlDocument Doc = new XmlDocument(); Doc.LoadXml("<root><a>12.55</a><b>Test</b></root>"); // 为根节点添加json命名空间声明(如果不存在) if (Doc.DocumentElement.GetNamespaceOfPrefix("json") == null) { XmlAttribute nsAttribute = Doc.CreateAttribute("xmlns", "json", "http://www.w3.org/2000/xmlns/"); nsAttribute.Value = jsonNamespace; Doc.DocumentElement.Attributes.Append(nsAttribute); } // 创建关联json命名空间的Type属性 XmlAttribute typeAttribute = Doc.CreateAttribute("json", "Type", jsonNamespace); typeAttribute.Value = "Decimal"; // 获取目标<a>节点并添加属性 XmlNode targetNode = Doc.SelectSingleNode("//a"); targetNode.Attributes.Append(typeAttribute); // 输出结果 Console.WriteLine(Doc.OuterXml);
输出结果
<root xmlns:json="http://james.newtonking.com/projects/json"> <a json:Type="Decimal">12.55</a> <b>Test</b> </root>
原代码问题说明
你之前的代码仅设置了att.Prefix = "json",但未指定att.NamespaceURI,XML规范要求前缀必须与命名空间URI绑定才能生效,否则解析器会自动丢弃前缀,最终输出无前缀的Type="Decimal"。
内容的提问来源于stack exchange,提问作者BenjaminR
相关产品推荐
相关产品推荐

