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

但是,如果 value 具有某些字符,则 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 回答