实体转Xml存储和遍历所有Xml节点
public class Student
{
public string First { get; set; }
public string Last { get; set; }
public int ID { get; set; }
public string Street { get; set; }
public string City { get; set; }
public List<int> Scores;
}
List<Student> students = new List<Student>() {
new Student {First="Svetlana",
Last="Omelchenko",
ID=111,
Street="123 Main Street",
City="Seattle",
Scores= new List<int> {97, 92, 81, 60}},
new Student {First="Claire",
Last="O’Donnell",
ID=112,
Street="124 Main Street",
City="Redmond",
Scores= new List<int> {75, 84, 91, 39}},
new Student {First="Sven",
Last="Mortensen",
ID=113,
Street="125 Main Street",
City="Lake City",
Scores= new List<int> {88, 94, 65, 91}}
};
将此students对象转换为Xml文本:
var studentsToXML = new XElement("root",
from s in students
let x = string.Format("{0},{1},{2},{3}", s.Scores[0], s.Scores[1], s.Scores[2], s.Scores[3])
select new XElement("student",
new XElement("First", s.First),
new XElement("Street", s.Street),
new XElement("City", s.City)
)
);
得到如下Xml文本:
<root>
<student>
<First>Svetlana</First>
<Street>123 Main Street</Street>
<City>Seattle</City>
</student>
<student>
<First>Claire</First>
<Street>124 Main Street</Street>
<City>Redmond</City>
</student>
<student>
<First>Sven</First>
<Street>125 Main Street</Street>
<City>Lake City</City>
</student>
</root>
存入磁盘指定位置:
using (FileStream fs = new FileStream(@"D:\X.XML", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
byte[] Buf = Encoding.Default.GetBytes(studentsToXML.ToString());
fs.Write(Buf, 0, Buf.Length);
}
遍历所有节点,找到指定节点的值:
static void FindElement(XmlNodeList _Nodes, string _CompareValue)
{
/*********** 第一种方法 ***********/
//foreach (XmlNode item in _Nodes)
//{
// if (item.Name == _CompareValue)
// Console.WriteLine("\r" + _CompareValue+"\r"+item.InnerText);
// else
// FindElement(item.ChildNodes, _CompareValue);
//}
/*********** 第二种方法 ***********/
_Nodes.Cast<XmlNode>().ToList<XmlNode>().ForEach(p =>
{
if (p.Name == _CompareValue)
{
Console.WriteLine();
Console.WriteLine("\t" + p.Name + "" + p.InnerText);
}
else
{
FindElement(p.ChildNodes, _CompareValue);
}
});
}
调用:
System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
xd.Load(@"D:\X.XML");
FindElement(xd.ChildNodes as XmlNodeList, "City");
本博客内容,如需转载请务必保留超链接。Contact Me:Mail此处省略好几个字...