所以我试图将Xml文档填充到一个对象列表中,我设法检索单个节点,但问题是我想选择几个!
这是对象
public class Item
{
public string Title{get;set;}
public string Date{get;set;}
}
这是XML
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfFeed xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<XmlItem Name="Test">
<Items>
<SubItem>
<Title>Some Title</Title>
<Date>Fri, 30 Oct</Date>
</SubItem>
<SubItem>
<Title>Some Title</Title>
<Date>Fri, 30 Oct</Date>
</SubItem>
</items>
</XmlItem>
</ArrayOfFeed>
这是我的代码。正如我之前所说,我设法只选择XML中的第一个子项,我想选择所有子项。试图玩弄它但到目前为止没有成功。
var itemToFind = "Test"
XDocument doc = XDocument.Load(location);
IEnumerable<Item> result = (from c in doc.Descendants("XmlItem")
where c.Attribute("Name").Value == itemToFind
let r = c.Element("Items")
let z = r.Element("SubItem")
select new Item()
{
Title = (string)z.Element("Title"),
Date = (string)z.Element("Date"),
}).ToList();
return result;
非常感谢帮助:)
答案 0 :(得分:0)
我比XDocuments更熟悉XmlDocuments,但这就是我要做的事情:
SelectNodes
方法获取节点集合,参数为XPath
到您希望在集合中的节点 - 我假设您要查找所有节点{{1具有Name =&#34; Test&#34;。XmlItem
(从XmlNode
返回XmlNodeList
),您需要使用SelectNodes
获取所有SelectNodes
个节点SubItems
)并创建新项目,并使用SelectSingleNode方法获取标题和日期值。答案 1 :(得分:0)
试试这个。 Items的结束标记需要大写I.我使用ParseExact将日期字符串转换为DateTime。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<ArrayOfFeed xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<XmlItem Name=\"Test\">" +
"<Items>" +
"<SubItem>" +
"<Title>Some Title</Title>" +
"<Date>Fri, 30 Oct</Date>" +
"</SubItem>" +
"<SubItem>" +
"<Title>Some Title</Title>" +
"<Date>Fri, 30 Oct</Date>" +
"</SubItem>" +
"</Items>" +
"</XmlItem>" +
"</ArrayOfFeed>";
XDocument doc = XDocument.Parse(xml);
string itemToFind = "Test";
List<Item> items = doc.Descendants("XmlItem").Where(x => x.Attribute("Name").Value == itemToFind).Descendants("SubItem").Select(y => new Item
{
Title = y.Element("Title").Value,
Date = DateTime.ParseExact(y.Element("Date").Value, "ddd, dd MMM", System.Globalization.CultureInfo.InvariantCulture)
}).ToList();
}
}
public class Item
{
public string Title { get; set; }
public DateTime Date { get; set; }
}
}