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

C#XML创建与节点对象引用

2013-10-24 10:55 330 查看
我们在创建xml过程中会遇到不同的级别有相同节点的情况。如下面的xml:

<?xml version="1.0" encoding="GBK">

<goods>

<price>$3/kg</price>

<sub>

  <weight>88kg</weight>

  <price>$3/kg</price>

</sub>

</goods>

标记为绿色的两个节点处于不同的级别,但是都引用了相同的XmlNode对象,于是我们写出如下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace XMLTest
{
class Program
{
static void Main(string[] args)
{
XmlDocument myXML = new XmlDocument();
XmlDeclaration myDeclaration = myXML.CreateXmlDeclaration("1.0", "GBK", null);
myXML.AppendChild(myDeclaration);
XmlNode goods = myXML.CreateNode(XmlNodeType.Element,"goods",null);
myXML.AppendChild(goods);
XmlNode price = myXML.CreateNode(XmlNodeType.Element, "price", null);
price.InnerText = "$3/kg";
goods.AppendChild(price);
XmlNode sub = myXML.CreateNode(XmlNodeType.Element, "sub", null);
goods.AppendChild(sub);

XmlNode weight = myXML.CreateNode(XmlNodeType.Element, "weight", null);
weight.InnerText = "88kg";
sub.AppendChild(weight);

sub.AppendChild(price);

Console.WriteLine(myXML.InnerXml);
Console.ReadKey();
}
}
}


在代码中我们创建了同一个对象price,然后再不同的地方,利用AppendChild去引用,但是结果你会发现结果是:

<goods>

<sub>

  <weight>88kg</weight>

  <price>$3/kg</price>

</sub>

</goods>

我的理解是,xml文档在创建过程时在内存中采用树状结构来构建,所以在调用过程中会导致前面调用该对象的链接失效。

解决方法: 重新复制一个对象。XmlNode price1 = price.Clone();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐