1

我有一个 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 确定元素“关闭”标记何时出现?

4

2 回答 2

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);
于 2013-08-12T11:23:08.117 回答
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>.

于 2013-08-12T11:38:18.293 回答