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

How to add attributes to xml using XmlDocument in c# .net CF 3.5(如何在 c# .net CF 3.5 中使用 XmlDocument 向 xml 添加属性)
本文介绍了如何在 c# .net CF 3.5 中使用 XmlDocument 向 xml 添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I need to create an attribute "abc" with the prefix "xx" for an element "aaa". The following code adds the prefix but it also adds the namespaceUri to the element.

所需输出:

<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"属性的声明应该在根节点中完成,如:

And the declaration of the "xx" attribute should be done in the root node like :

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

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

How can if get the output in the deisred format? If the xml is not in this desired format then it cannot be processed anymore..

谁能帮忙?

谢谢,维姬

推荐答案

相信直接在根节点上设置相关属性就可以了.这是一个示例程序:

I believe it's just a matter of setting the relevant attribute directly on the root node. Here's a sample program:

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# .net CF 3.5 中使用 XmlDocument 向 xml 添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)
How to store delegates in a List(如何将代表存储在列表中)
How delegates work (in the background)?(代表如何工作(在后台)?)
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)