c# - 如何在 c# .net CF 3.5 中使用 XmlDocument 向 xml 添加属性

标签 c# .net xml windows-mobile xsd

我需要为元素“aaa”创建一个前缀为“xx”的属性“abc”。以下代码添加了前缀,但它也将 namespaceUri 添加到元素。

要求的输出:

<mybody>
<aaa xx:abc="ddd"/>
<mybody/>

我的代码:

  XmlNode node = doc.SelectSingleNode("//mybody");
  XmlElement ele = doc.CreateElement("aaa");

  XmlAttribute newAttribute = doc.CreateAttribute("xx","abc",namespace);              
  newAttribute.Value = "ddd";

  ele.Attributes.Append(newAttribute);

  node.InsertBefore(ele, node.LastChild);

上面的代码生成:

<mybody>
<aaa xx:abc="ddd" xmlns:xx="http://www.w3.org/1999/XSL/Transform"/>
<mybody/>

期望的输出是

<mybody>
<aaa xx:abc="ddd"/>
<mybody/>

并且“xx”属性的声明应该在根节点中完成,例如:

<ns:somexml xx:xsi="http://www.w3.org/1999/XSL/Transform"  xmlns:ns="http://x.y.z.com/Protocol/v1.0">

如何获得所需格式的输出?如果 xml 不是这种所需的格式,则无法再对其进行处理。

有人能帮忙吗?

谢谢, 维琪

最佳答案

我相信这只是直接在根节点上设置相关属性的问题。这是一个示例程序:

using System;
using System.Globalization;
using System.Xml;

class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        XmlElement root = doc.CreateElement("root");

        string ns = "http://sample/namespace";
        XmlAttribute nsAttribute = doc.CreateAttribute("xmlns", "xx",
            "http://www.w3.org/2000/xmlns/");
        nsAttribute.Value = ns;
        root.Attributes.Append(nsAttribute);

        doc.AppendChild(root);
        XmlElement child = doc.CreateElement("child");
        root.AppendChild(child);
        XmlAttribute newAttribute = doc.CreateAttribute("xx","abc", ns);
        newAttribute.Value = "ddd";        
        child.Attributes.Append(newAttribute);

        doc.Save(Console.Out);
    }
}

输出:

<?xml version="1.0" encoding="ibm850"?>
<root xmlns:xx="http://sample/namespace">
  <child xx:abc="ddd" />
</root>

关于c# - 如何在 c# .net CF 3.5 中使用 XmlDocument 向 xml 添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3405284/

相关文章:

c# - 将 RSI 从 pinescript 转换为 C#?

c# - 如何将 dbcontext/工作单元发送到 Hangfire 作业过滤器

javascript - 相当于 C# 中的 Javascript Yield* 委托(delegate)给另一个迭代器?

c# - 在 C# 中使用自定义序列化时如何控制 XML 元素的名称?

java - 在 Android 中解析 XML

android - 透明阴影 View

c# - 为什么我无法从 JArray 中删除元素?

c# - 获取特定国家/地区的当前日期和时间

c# - c# 100个应用同时写入日志时如何实现同步

c#.net 32​​ 位应用程序不适用于 64 位操作系统