我有一个XML文档,我循环并将输出解析为控制台。所有工作等,但我需要能够确定标签从父节点关闭的位置。例如:
<activity date="2013-07-05T06:42:35" name="open" host="55.555.20.5554">
<user id="EU-user@email.co.uk" name="J Bloggs" memberType="E" />
<storageObject docId="4130-7447-0000" name="Documents name" size="1903885" fileExtension="pdf">
<cabinet name="Client Cabinet">NG-XXXXXX</cabinet>
<Matter>0000</Matter>
<Client>X54654</Client>
<Author>L Bloggs</Author>
</storageObject>
</activity>
在每个活动结束时,我希望能够输出一行来确定每个活动结束的控制台输出。
有没有办法确定何时使用XDocument发生元素“close”标记?
答案 0 :(得分:1)
您不需要确定标签关闭的位置。 XDocument将为您确定:
var activities = from a in xdoc.Descendants("activity")
let u = a.Element("user")
let so = a.Element("storageObject")
select new {
Date = (DateTime)a.Attribute("date"),
Name = (string)a.Attribute("name"),
User = new {
Id = (string)u.Attribute("id"),
Name = (string)u.Attribute("name")
},
Storage = new {
Client = (string)so.Element("Client")
}
//...
};
它会创建强类型对象,您可以迭代它们:
foreach(var activity in activities)
Console.WriteLine("{0} on {1}", activity.Name, activity.Date);
答案 1 :(得分:0)
怎么样:
// Load document into XDocument instance.
var doc = XDocument.Load("source.txt");
// query for all <activity> element.
var activities = doc.Root.Elements("activity");
// add XComment after each of them.
foreach (var a in activities)
{
a.AddAfterSelf(new XComment("------------"));
}
// Print document into console.
Console.WriteLine(doc.ToString());
每<!--- - - - - - - - - - - - -->
后打印</activity>
。