日期:2014-05-19  浏览次数:20830 次

关于用C#对一树型的XML树型文件的操作
麻烦大家能不能帮我看看一个树型的XML文件的相关操作
XML因为比较复杂,所以我放在下面的地址,麻烦各位下载看下

http://www.szqyjy.com/TEMP/XML.rar

现在我的难点是怎么对其数据进行操作:
1.添加一个新的实例到XML中;
2.对树型XML中的某个实例的节点的增减

我参考了些资料,可是还是没法下手,不得已,只能寻求下帮助,请各位帮忙看看.

如果分不够我可以再开.谢谢了.

------解决方案--------------------
up
------解决方案--------------------
Xml.XmlElement已经提供了大量操作XML的方法,要操作XML首选是要懂得xPath
------解决方案--------------------
试试将XML反序列化为一个对象,对对象进行你要的操作,再序列化回XML
------解决方案--------------------
using System;
using System.Xml.Serialization;
using System.Xml;
using System.IO;

namespace XMLOperate
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
try
{
// XmlTextWriter writer = new XmlTextWriter( "coil.xml ", null);
// writer.Formatting = Formatting.Indented;
// writer.WriteStartElement( "coils ");
// writer.WriteEndElement();
// writer.Flush();
// writer.Close();

XmlDocument doc = new XmlDocument();
doc.Load( "coil.xml ");
XmlElement root = doc.DocumentElement;

// Add_Node(doc,root);
Query_Node(root);
//Delete_Node(doc,root);
// Console.WriteLine( "Begin.................... ");
show_child_node(root);
// Console.WriteLine( "End...................... ");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
Console.ReadLine();
}
}

public static void Add_Node(XmlDocument doc, XmlNode root)
{
XmlElement masterelem = doc.CreateElement( "coil ");
root.AppendChild(masterelem);

XmlElement detailelem = doc.CreateElement( "coil_id ");
detailelem.InnerText= "A131 ";
masterelem.AppendChild(detailelem);

Console.WriteLine( "sucessful 1 ");

detailelem = doc.CreateElement( "coil_length ");
detailelem.InnerText= "12345 ";
masterelem.AppendChild(detailelem);

Console.WriteLine( "sucessful 2 ");

detailelem = doc.CreateElement( "coil_width ");
detailelem.InnerText= "1780 ";
masterelem.AppendChild(detailelem);

detailelem = doc.CreateElement( "coil_thickness ");
detailelem.InnerText= "500 ";
masterelem.AppendChild(detailelem);

detailelem = doc.CreateElement( "coil_weight ");
detailelem.InnerText= "21345 ";
masterelem.AppendChild(detailelem);

doc.Save( "coil.xml ");

Console.WriteLine( "append finish! ");
}

public static bool Query_Node(XmlNode rootNode)
{

XmlNode elem = rootNode.SelectSingleNode( "descendant::coil[coil_id= 'A131 '] ");
if (elem!=null)
{
Console.WriteLine(elem.ChildNodes[1].InnerText.ToString());
return true;
}
else
{
Console.WriteLine( "not found node ");
return false;
}
}

public static void Delete_Node(XmlDocument doc, XmlNode rootNode)
{
if (Query_Node(rootNode))
{
XmlNode elem = rootNode.SelectSingleNode( "descendant::coil[coil_id= 'A121 '] ");