2017-11-18 1 views
2

XDocumentには、 'x'、 'y'、 'x1'、 'y1'、 'z'、および ' Z1' :すべての要素をループして、特定の属性をチェックせず、文書全体からのx 『属性の値のみを抽出するための最も簡単な推奨される方法は何XDocument全体からの属性の抽出

<?xml version="1.0" encoding="utf-8"?> 
<shapes> 
    <shape> 
    <connections /> 
    <foreground> 
     <strokewidth width="0.1" /> 
     <path> 
     <move x="1395.6" y="84.6" /> 
     <line x="80.1" y="84.6" /> 
     <curve x1="75.1" y1="84.6" x2="71.1" y2="88.6" x3="71.1" y3="93.6" /> 
     <line x="71.1" y="402.6" /> 
     <close /> 
     </path> 
     <fillstroke /> 
    </foreground> 
    </shape> 
</shapes> 

』?座標であるため :

float[] x= {1395.6, 80.1, 71.1}; 
float[] x1 = {75.1}; 

そして、 'Y'、 'Y1' の同じ、...


EDIT:与えられたXMLは、理想的には 'X' 座標のリストでしまいます常に「葉」のXML要素で、私は最終的に使用:

return fileXml.Root.Descendants() 
       .Where(e => e.HasElements == false) // leaf element 
       .Where(e => e.Attribute("x") != null) 
       .Select(c => c.Attribute("x").Value).Select(float.Parse) 
       .ToList(); // or .ToArray(); 

それは同様にヘルパー関数でラップすることができます。

答えて

2

xpathを使用できます。 XPath式//@xは名前xですべての属性にマッチします:

var doc = XDocument.Parse(yourXml); 
float[] x = ((IEnumerable)doc.XPathEvaluate("//@x")) 
      .OfType<XAttribute>() 
      .Select(c => float.Parse(c.Value, CultureInfo.InvariantCulture)) 
      .ToArray(); 
1

一部の人々は、このソリューションが好きであり、他方はないかもしれません。これは少し複雑ですが、XML全体をxml、linを使ってx、yペアに解析します。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 


namespace ConsoleApplication1 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      XDocument doc = XDocument.Load(FILENAME); 

      List<KeyValuePair<string, List<KeyValuePair<double, double>>>> instructions = new List<KeyValuePair<string, List<KeyValuePair<double, double>>>>(); 

      foreach (XElement instruction in doc.Descendants("path").FirstOrDefault().Elements()) 
      { 
       List<KeyValuePair<double, double>> points = new List<KeyValuePair<double, double>>(); 
       for (int i = 0; i < instruction.Attributes().Count(); i += 2) 
       { 
        points.Add(new KeyValuePair<double,double>((double)instruction.Attributes().Skip(i).FirstOrDefault(), (double)instruction.Attributes().Skip(i + 1).FirstOrDefault())); 
       } 
       instructions.Add(new KeyValuePair<string, List<KeyValuePair<double,double>>>(instruction.Name.LocalName, points)); 
      } 

     } 
    } 
} 
関連する問題