0

基本的に、私は次のようなxmlファイル形式を持っています:

<?xml version="1.0" encoding="utf-8" ?>
<retentions>
   <client id="1544">
      <facility id="5436">
         <retention period="23" />
      </facility>
   </client>
   <client id="7353">
      <facility id="3450">
        <retention period="3" />
     </facility>
   </client>
</retentions>

「1554」、「5436」、「23」など、すべての属性のすべての値を取得したい。

XMLDocument の代わりに XDocument を使用してください。私のコードは間違っています:

XDocument XDoc = XDocument.Load("my.xml");
   IEnumerable<XElement> results = (from el in XDoc.Root.Elements("retentions")
                                         select el);

更新:(辞書を使用)

var g = from element in XDoc.Descendants("client")
                from ID in element.Attributes("id")
                from Facility in element.Attributes("facility")
                from Period in element.Attributes("period")
                select new { Key = ID.Value, Value = Period.Value };
4

2 に答える 2

4

xml ドキュメントからすべての属性を取得する 1 行:

var attributes = ((IEnumerable)xdoc.XPathEvaluate("//@*"))
                      .Cast<XAttribute>().Select(a => (string)a);

UPDATE (すべてのノード属性の辞書)

var attributes = xdoc.Descendants()
                    .GroupBy(e => e.Name)
                    .ToDictionary(g => g.Key.LocalName,
                                  g => g.SelectMany(x => x.Attributes())
                                        .Select(a => (string)a)
                                        .ToList());

List<string> attributesOfClient = attributes["client"];
于 2013-01-21T21:20:55.830 に答える
2

要素の属性を取得するには:

XElement xElement;
IEnumerable attributes = xElement.Attributes();

ドキュメントのすべての要素を取得するには:

XDocument xDocument;
IEnumerable<XElement> elements = xDocument.Descendants();

次に、LINQ を使用します。すべての値は次のとおりです。

from element in xDocument.Descendants()
from attribute in element.Attributes()
select attribute.Value;

これは、あなたの望むことですか?

アップデート

var dictionary = xDocument.Descendants("client").ToDictionary(element => element, element =>
    (from descendant in element.Descendants()  // Gets descendant elements of element
    from attribute in descendant.Attributes()  // Gets all the attributes of the descendant
    select attribute.Value).ToList());

更新 2

var g = XDoc.Descendants("client")
        .ToDictionary(element => element.Attribute("id").Value,
                      element => new 
                                 {                                 
                                     element.Descendants("facility").First().Attribute("id").Value, 
                                     element.Descendants("retention").First().Attribute("period").Value 
                                  });
于 2013-01-21T21:11:18.067 に答える