如何使用Linq to XML解析XML字符串并定位值以指定字母开头的所有节点?
本文关键字:XML 开头 节点 解析 to Linq 何使用 字符 字符串 定位 串并 | 更新日期: 2023-09-27 18:12:01
给定一个XML文本字符串,如
"<?xml version='"1.0'" encoding='"UTF-8'"?>" +
"<directory dirname='"c'">" +
"<directory dirname='"documents'">" +
"<directory dirname='"daves projects 2015'" />" +
"<directory dirname='"vics projects 2015'" />" +
"<directory dirname='"daves projects 2014'" />" +
"</directory>" +
"<directory dirname='"daves projects archive'" />" +
"</directory>";
当前使用Linq to XML解析该字符串以返回以"dave"开头的目录名列表的首选方法是什么?或者有比使用Linq来XML更好的方法
我需要一个像下面这样的字符串列表的结果;
dave projects 2015
dave projects 2014
dave projects archive
我试着使用下面的语句;
public static void Main(string[] args)
{
string xml =
"<?xml version='"1.0'" encoding='"UTF-8'"?>" +
"<directory dirname='"c'">" +
"<directory dirname='"documents'">" +
"<directory dirname='"daves projects 2015'" />" +
"<directory dirname='"vics projects 2015'" />" +
"<directory dirname='"daves projects 2014'" />" +
"</directory>" +
"<directory dirname='"daves projects archive'" />" +
"</directory>";
var Folders = ParseXmlString(xml, "dave");
foreach (XElement name in Folders)
Console.WriteLine(name.Value);
}
private static List<XElement> ParseXmlString(string xmlStr, string searchValue)
{
List<XElement> result = new List<XElement>();
try
{
var str = XElement.Parse(xmlStr);
result = str.Elements("directory").Where(x => x.Element("dirname").Value.StartsWith(searchValue)).ToList();
}
catch (Exception ex)
{
throw ex;
}
return result;
}
但是结果总是空的。
有什么建议吗?
将函数更改如下…
-
在调用方法中,将类型更改为
foreach (XAttribute name in Folders)
-
修改ParseXmlString如下所示。
private static List<XAttribute> ParseXmlString(string xmlStr, string searchValue) { List<XAttribute> result = new List<XAttribute>(); try { XDocument doc = XDocument.Parse(xmlStr); result = doc.Descendants("directory") .Attributes("dirname") .Where(x => x.Value.StartsWith("d")) .ToList(); } catch (Exception ex) { throw ex; } return result; }
让我知道这是否有帮助。
在VB中,使用XElement,它将是
Dim xe As XElement = XElement.Parse(xml)
Dim ie As IEnumerable(Of String) = From el In xe...<directory>
Where el.@dirname.StartsWith("dave")
Select el.@dirname