用C#创建一个xml文件,自定义的xmlns没有写到元素当中去,为什么?

nsareio 2014-04-14 05:55:55
我有下面一段代码:

class Program
{
static void Main(string[] args)
{
XmlDocument document = new XmlDocument();
document.AppendChild(document.CreateXmlDeclaration("1.0", "UTF-8", ""));
XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable);
//manager.AddNamespace("haha", "http://schemas.microsoft.com/BizTalk/2003");
XmlElement root = document.CreateElement("my:root", "haha:http://schemas.microsoft.com/BizTalk/2003");
document.AppendChild(root);

XmlElement newNode = document.CreateElement("abc","my");
newNode.InnerText = "hello";
root.AppendChild(newNode);
XmlElement newNode1 = document.CreateElement("xyz","my");
newNode1.InnerText = "world";
root.AppendChild(newNode1);
document.Save(@"d:\test.xml");
}
}

运行的结果是产生了一个xml,但是有点不符合我的预期

<?xml version="1.0" encoding="UTF-8"?>
<my:root xmlns:my="haha:http://schemas.microsoft.com/BizTalk/2003">
<abc xmlns="my">hello</abc>
<xyz xmlns="my">world</xyz>
</my:root>

而我期待的是内嵌的两个元素是

<my:abc>hello</my:abc>
<my:xyz>world</my:xyz>

看起来我的C#代码在写入abc和xyz这两个tag的时候,是用了xmlnm="my"这样的写法。
(1)这个写法和my:abc的效果是一样的吗? 还是有所不同呢?
(2)如果我希望代码生成my:abc这样的标签,代码改怎么改?
...全文
267 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
dalmeeme 2014-04-14
  • 打赏
  • 举报
回复
		XmlDocument document = new XmlDocument();
		document.AppendChild(document.CreateXmlDeclaration("1.0", "UTF-8", ""));
		string namespaceUrl = "haha:http://schemas.microsoft.com/BizTalk/2003";
		XmlElement root = document.CreateElement("my", "root", namespaceUrl);
		document.AppendChild(root);
		XmlElement newNode = document.CreateElement("my", "abc", namespaceUrl);
		newNode.InnerText = "hello";
		root.AppendChild(newNode);
		XmlElement newNode1 = document.CreateElement("my", "xyz", namespaceUrl);
		newNode1.InnerText = "world";
		root.AppendChild(newNode1);
		document.Save(@"d:\test.xml");
最后得到:
<?xml version="1.0" encoding="UTF-8" ?> 
 <my:root xmlns:my="haha:http://schemas.microsoft.com/BizTalk/2003">
  <my:abc>hello</my:abc> 
  <my:xyz>world</my:xyz> 
  </my:root>
nsareio 2014-04-14
  • 打赏
  • 举报
回复
自己顶起来一下!

111,125

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧