永发信息网

linq to xml 按 节点属性查找节点方法

答案:2  悬赏:30  手机版
解决时间 2021-03-08 00:09
  • 提问者网友:欲劫无渡
  • 2021-03-07 08:41









假设节点名必须是这个
能不能通过id来查找 所有节点1级2级.....全部
比如我要找001002001这个节点,该怎么找
最佳答案
  • 五星知识达人网友:蓝房子
  • 2021-03-07 09:04
贴到vs里面试一下吧

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace LinqToXMLDemo
{
class Program
{
static void Main(string[] args)
{
string idPath = "001002001";
GetElement(idPath);
Console.ReadLine();
}

public static XElement GetElement(string idPath)
{
// 加载 xml 文件
XElement element = XElement.Load("Category.xml");

// 分解参数: 三位一个节点
IList ids = new List();
while (idPath.Length > 0)
{
ids.Add(idPath.Substring(0, 3));
idPath = idPath.Remove(0, 3);
}

// 根据id集合寻找xml元素
string currentId = string.Empty;
foreach (string id in ids)
{
currentId = currentId + id;
element = element.Elements().Where(e => e.Attribute("id").Value == currentId).FirstOrDefault();
if (element == null)
throw new Exception("找不到id:" + currentId);
}

return element;
}
}
}












全部回答
  • 1楼网友:底特律间谍
  • 2021-03-07 10:06
xdocument doc = xdocument.load("demo.xml"); var text = from t in doc.descendants("用户") //定位到节点 .where(w => w.element("姓名").value.contains('张')) //若要筛选就用上这个语句 select new { name = t.element("姓名").value }; foreach (var a in text) { console.writeline(a.name); }
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯