xml根据条件获取指定节点 C#

[复制链接]
查看11 | 回复2 | 2009-9-4 09:46:26 | 显示全部楼层 |阅读模式
很容易! XML的操作只要会了其实很简单!private void Form1_Load(object sender, EventArgs e)
{
if (InitXml(@"D:\Work\CharpApp\1.xml"))
{
string k1 = GetValue("1", "href");
k1 = GetValue("1", "imageurl");
string k2 = GetValue("2", "href");
k2 = GetValue("2", "imageurl");
}
}
System.Xml.XmlDocument doc = null;
private bool InitXml(string path)
{
try
{
doc = new System.Xml.XmlDocument();
doc.Load(path);
return true;
}
catch
{
return false;
}
}
private string GetValue(string Name,string ID)
{
string value = "";
System.Xml.XmlNodeList nl = doc.DocumentElement.ChildNodes;
foreach (System.Xml.XmlNode nd in nl)
{
string name = nd.Attributes.GetNamedItem("name").Value;
if (null != name && name.Trim() != "")
{
if (name.Trim() == Name.Trim())
{
value= nd.Attributes.GetNamedItem(ID).Value;
break;
}
}
}
return value;
}
回复

使用道具 举报

千问 | 2009-9-4 09:46:26 | 显示全部楼层
linq to xml是很好的选择using System;using System.Collections.Generic;using System.Linq;using System.Xml.Linq;using System.Text;using System.IO;namespace ConsoleApplication1{
public class Program
{
static void Main()
{
StringReader sr = new StringReader(@"");
XDocument xd = XDocument.Load(sr);//可以直接load某个文件//这里就是linq查询语句了
var xes = (from ele in xd.Root.Elements()
where ele.Attribute("name").Value == "1"
select ele
);
foreach (var xe in xes)
Console.WriteLine(xe.ToString());
sr.Close();
Console.Read();
}
}}
回复

使用道具 举报

千问 | 2009-9-4 09:46:26 | 显示全部楼层
假如文件名为 myxml.xml XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("myxml.xml");
XmlElement xet = xmlDoc.SelectSingleNode(
"//slider/item[@name='1']")//或者其它
as XmlElement;
if (xet == null)
{}else{}xmlpath 最快
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行