当前位置: 编程技术>.net/c#/asp.net
C#通过XML节点属性/属性值读取写入XML操作代码实例
来源: 互联网 发布时间:2014-10-24
本文导语: 1.XML的内容如下: 代码如下: 欢迎您!智慧服务,互动体验...... 微软雅黑 Yellow 48 Videos/ICV.mp4 Videos/ygsqxcp.mp4 Videos/iBaosight.mp4 ...
1.XML的内容如下:
代码如下:
欢迎您!智慧服务,互动体验......
微软雅黑
Yellow
48
Videos/ICV.mp4
Videos/ygsqxcp.mp4
Videos/iBaosight.mp4
Videos/goodlift.mp4
Picture/main.jpg
2.获得XML文档
代码如下:
private static string url = AppDomain.CurrentDomain.SetupInformation.ApplicationBase+"Config\config.xml";
private XmlDocument xmlDoc;
private XmlNode root;
public static string Title;
public XMLHandler()
{
xmlDoc = new XmlDocument();
LoadConfig();
}
private void LoadConfig()
{
try
{
xmlDoc.Load(url);
root = xmlDoc.SelectSingleNode("root");
}
catch (Exception e)
{
throw e;
}
}
3.通过属性名称读取XML节点中的内容
代码如下:
public TitleModel GetTitle()
{
try
{
TitleModel title = new TitleModel();
XmlNode node = root.FirstChild;
if(node!=null)
{
foreach (XmlNode nd in node.ChildNodes)
{
XmlElement element = (XmlElement)nd;
if (element.GetAttribute("name") == "显示文字")
{
title.Title = nd.InnerText;
}
else if (element.GetAttribute("name") == "字体尺寸")
{
title.FontSize = Convert.ToInt32(nd.InnerText);
}
else if (element.GetAttribute("name") == "颜色")
{
title.FontColor = FontColor(nd.InnerText);
}
else if (element.GetAttribute("name") == "字体")
{
title.FontFamily = nd.InnerText;
}
}
}
return title;
}
catch (Exception e)
{
throw e;
}
}
4.通过属性读取XML中节点的属性值
代码如下:
public List GetMenuString()
{
try
{
List list=new List();
XmlNode menu = root.ChildNodes[1];
if (menu != null)
{
foreach (XmlNode node in menu.ChildNodes)
{
XmlElement element = (XmlElement)node;
list.Add(element.GetAttribute("name"));
}
}
return list;
}
catch (Exception e)
{
throw e;
}
}
5.通过节点获取XML节点中的内容
代码如下:
public string GetMainBackground()
{
string url ="Images/mainjpg";
try
{
XmlNode node = root.LastChild;
if (node != null)
{
url = node.InnerText;
}
return url;
}
catch (Exception e)
{
throw e;
}
}