怎么读取XML指定节点下的值?

hanwuji502 2010-11-11 04:33:47
<Customers>
<User name="aaa" age="21">
<Address>
Shanghai
</Address>
<Technology>
C#
</Technology>
</User>
<User name="bbb" age="22">
<Address>
Zhejiang
</Address>
<Technology>
javascript
</Technology>
</User>
<User name="ccc" age="23">
<Address>
Zhejiang
</Address>
<Technology>
Delphi
</Technology>
</User>
</Customers>

请问,我如果要获取 name="bbb" 的节点下面的 Address节点的值zhejiang,C#应该怎么写呢?
...全文
101 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
龍月 2010-11-11
  • 打赏
  • 举报
回复
可以根据xml path 来直接获取 此消息通过 【CSDN论坛 Winform测试版】 回复!龙月.NET的博客
cdglynn 2010-11-11
  • 打赏
  • 举报
回复
序列化
PxxxP 2010-11-11
  • 打赏
  • 举报
回复
            string xml = @"<Customers>
<User name=""aaa"" age=""21"">
<Address>
Shanghai
</Address>
<Technology>
C#
</Technology>
</User>
<User name=""bbb"" age=""22"">
<Address>
Zhejiang
</Address>
<Technology>
javascript
</Technology>
</User>
<User name=""ccc"" age=""23"">
<Address>
Zhejiang
</Address>
<Technology>
Delphi
</Technology>
</User>
</Customers>";


XDocument Doc = XDocument.Parse(xml);
var query = Doc.Descendants("User").Where(x => x.Attribute("name").Value == "bbb").Select(x => x.Element("Address").Value);
foreach (var v in query)
{
Console.WriteLine(v.ToString());
q107770540 2010-11-11
  • 打赏
  • 举报
回复

void Main()
{
string xml = @"<Customers>
<User name=""aaa"" age=""21"">
<Address>
Shanghai
</Address>
<Technology>
C#
</Technology>
</User>
<User name=""bbb"" age=""22"">
<Address>
Zhejiang
</Address>
<Technology>
javascript
</Technology>
</User>
<User name=""ccc"" age=""23"">
<Address>
Zhejiang
</Address>
<Technology>
Delphi
</Technology>
</User>
</Customers>";
XElement xmlPage = XElement.Parse(xml);
var q = from x in xmlPage.Descendants("User")
where x.Attribute("name").Value == "bbb"
select x.Element("Address").Value;
q.ToList().ForEach(l=>Console.WriteLine(l));
}

/*
Zhejiang
*/
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 a82344626 的回复:]
System.Xml.XmlNode xn = xd.SelectSingleNode("User/[@name='ccc']/Address");
if (xn != null)
return xn.Attributes["Source"].Value;
[/Quote]
正解
sprc_lcl 2010-11-11
  • 打赏
  • 举报
回复
        string xmlStr = "....";
XmlDocument xd = new XmlDocument();
xd.LoadXml(xmlStr);
XmlNodeList xnlUser = xd.SelectNodes("Customers/User");
string bAddress = "";
foreach(XmlNode xnUser in xnlUser)
{
if(xnUser.Attributes["name"].Value == "bbb")
{
bAddress = xnUser.SelectSingleNode("Address").InnerText;
break;
}
}
a82344626 2010-11-11
  • 打赏
  • 举报
回复
System.Xml.XmlNode xn = xd.SelectSingleNode("User/[@name='ccc']/Address");
if (xn != null)
return xn.Attributes["Source"].Value;

111,129

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧