1

作成した xml ドキュメントを解析しようとしています。ただし、特定の文字があるxml.Descendants(value)場合は機能しませんvalue(スペースを含む、これは私の問題です)。

私のxmlは次のように構成されています:

<stockists>
  <stockistCountry country="Great Britain">
    <stockist>
      <name></name>
      <address></address>
    </stockist>
  </stockistCountry>
  <stockistCountry country="Germany">
    <stockist>
      <name></name>
      <address></address>
    </stockist>
  </stockistCountry>
  ...
</stockists>

解析用の C# コードは次のようになります。

string path = String.Format("~/Content/{0}/Content/Stockists.xml", Helper.Helper.ResolveBrand());
XElement xml = XElement.Load(Server.MapPath(path));

var stockistCountries = from s in xml.Descendants("stockistCountry")
                                select s;

StockistCountryListViewModel stockistCountryListViewModel = new StockistCountryListViewModel
{
    BrandStockists = new List<StockistListViewModel>()
};

foreach (var stockistCountry in stockistCountries)
{
    StockistListViewModel stockistListViewModel = new StockistListViewModel()
    {
        Country = stockistCountry.FirstAttribute.Value,
        Stockists = new List<StockistDetailViewModel>()
    };

    var stockist = from s in xml.Descendants(stockistCountry.FirstAttribute.Value) // point of failure for 'Great Britain'
                   select s;

    foreach (var stockistDetail in stockist)
    {
         StockistDetailViewModel stockistDetailViewModel = new StockistDetailViewModel
         {
             StoreName = stockistDetail.FirstNode.ToString(),
             Address = stockistDetail.LastNode.ToString()
         };

         stockistListViewModel.Stockists.Add(stockistDetailViewModel); 
     }

     stockistCountryListViewModel.BrandStockists.Add(stockistListViewModel);
 }

 return View(stockistCountryListViewModel);

Xml の解析に正しく取り組んでいるかどうか、属性にスペースを含めるべきではないかどうかなど、疑問に思っています。英国が解析できるように修正する方法

4

1 に答える 1

1

ただし、値に特定の文字が含まれている場合、xml.Descendants(value) は機能しません。

XElement.Descendants()ではなく、タグの XName が必要です。

実際、XML タグにスペースを含めることはできません。

ただし、サンプル XML には属性の値のみが含まれており、そのスペースは問題ありません。

アップデート:

私はあなたが必要だと思います

//var stockist = from s in xml.Descendants(stockistCountry.FirstAttribute.Value) 
//              select s;

var stockists = stockistCountry.Descendants("stockist");
于 2012-04-19T10:14:01.257 に答える