您的位置:首页 > 编程语言 > C#

C#处理带命名空间的XML

2008-11-28 11:23 387 查看
写入带命名空间的xml文本。

XmlDocument doc = new XmlDocument();

doc.LoadXml("<?xml version=/"1.0/" encoding=/"utf-8/"?><root></root>");

//namespace为空时,不能设置prefix

XmlElement ele = doc.CreateElement("bbs","hit","urn:bbs");

ele.InnerText = "100";

doc.DocumentElement.AppendChild(ele);

doc.Save("test1.xml");

空namespace的元素不能设置前缀。
保存后test1.xml内容:

<?xml version="1.0" encoding="utf-8"?>
<root>
<bbs:hit xmlns:bbs="urn:bbs">100 </bbs:hit>
</root>

读取带命名空间的xml文本。

XmlDocument doc = new XmlDocument();

//报错:“bbs”是未声明的命名空间

//doc.LoadXml("<?xml version=/"1.0/" encoding=/"utf-8/"?><root><bbs:hit>99</bbs:hit></root>");

doc.LoadXml("<?xml version=/"1.0/" encoding=/"utf-8/"?><root><bbs:hit xmlns:bbs=/"urn:bbs/">100</bbs:hit></root>");

XmlNode root = doc.DocumentElement;

XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);

xnm.AddNamespace("bbs", "urn:bbs");

XmlNode node = root.SelectSingleNode("bbs:hit", xnm);

if(node != null)

System.Console.WriteLine("found node :" + node.InnerText);

另一个读取的例子。

XmlDocument doc = new XmlDocument();

doc.LoadXml("<?xml version=/"1.0/" encoding=/"utf-8/"?><root xmlns=/"http://www.163.com/rss/0.9/"><news><title>这是标题</title></news></root>");

XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);

xnm.AddNamespace("bbs", "http://www.163.com/rss/0.9");

XmlNode root = doc.SelectSingleNode("bbs:root", xnm);

XmlNode news = root.SelectSingleNode("bbs:news",xnm);

//错误,取不到节点

//news = root.SelectSingleNode("news", xnm);

XmlNode title = doc.SelectSingleNode("bbs:root/bbs:news/bbs:title", xnm);

System.Console.WriteLine("root.InnerXml = " + root.InnerXml);

System.Console.WriteLine("news.InnerXml = " + news.InnerXml);

System.Console.WriteLine("title.InnerText = " + title.InnerText);

System.Console.ReadLine();

输出:
root.InnerXml = <news xmlns="http://www.163.com/rss/0.9"><title>这是标题</title>
</news>
news.InnerXml = <title xmlns="http://www.163.com/rss/0.9">这是标题</title>
title.InnerText = 这是标题

可见子节点也继承了父节点的命名空间。即使通过父节点root.SelectSingleNode()查找子节点,也必须提供命名空间。

接着上一个读取的例子,在root节点下添加子节点:

//必须传递第二个参数,否则创建的节点是<news xmlns="">

XmlElement news1 = doc.CreateElement("news", "http://www.163.com/rss/0.9");

XmlElement title1 = doc.CreateElement("title", "http://www.163.com/rss/0.9");

title1.InnerText = "新加的一个标题";

news1.AppendChild(title1);

root.AppendChild(news1);

doc.Save("test3.xml");

保存后的test3.xml内容:

<?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://www.163.com/rss/0.9">
<news>
<title>这是标题</title>
</news>
<news>
<title>新加的一个标题</title>
</news>
</root>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: