2013-11-24 52 views
1

我似乎无法弄清楚这个代码有什么问题......任何想法都是我做错了什么。 select返回一个具有所有null属性的项,即foreach循环只输入一次,而WMServer服务器[pick属性]设置为null。Linq to XML没有任何价值

var xdoc = XDocument.Load(@"pathtoxmlfile.xml"); 
var wms = from e2 in xdoc.Elements("GISImportConfig").Elements("BaseMapLayers") 
      select new 
      { 
       Url = (string)e2.Attribute("url"), 
       Enabled = (string)e2.Attribute("enabled"), 
       UserName = (string)e2.Attribute("username"), 
       Pasword = (string)e2.Attribute("password"), 
       Layers = e2.Elements("WMLayer") 
      }; 

foreach (var Config in wms) 
{ 
    WMServer server = new WMServer(); 
    server.ServerURL = Config.Url; 
    server.Enabled = Convert.ToBoolean(Config.Enabled); 
    server.UserName = Config.UserName; 
    server.Password = Config.Pasword; 

    foreach (var layers in Config.Layers) 
    { 
     WMLayer layer = new WMLayer(); 
     layer.Group = (string)layers.Attribute("group"); 
     layer.Enabled = Convert.ToBoolean(layers.Attribute("enabled")); 
     layer.Name = (string)layers.Attribute("name"); 
    } 
} 

XML:

<?xml version="1.0" encoding="utf-8" ?> 
<GISImportConfig OracleServer="*" OracleInstance="*" OracleSchema="*"> 
    <BaseMapLayers> 
    <WMServer url="https://example" enabled="true" username="someuser" password="somepass"> 
     <WMLayer name="0" enabled ="true" group="test"></WMLayer> 
     <WMLayer name="1" enabled ="true" group="test"></WMLayer> 
    </WMServer> 
    <WMServer url="server2" enabled="false" username="" password=""> 
     <WMLayer name="test2" enabled ="true" group="test"></WMLayer> 
    </WMServer> 
    </BaseMapLayers> 
</GISImportConfig> 
+0

'Select'不能改变原始元素的数量,这意味着你必须查看源代码... –

+0

我认为你在'xml'中有一个额外的''(不是与问题有关)。 – Chris

+0

谢谢,不在源XML文件。我编辑了这个问题。 – will

回答

2

你只有一个结果得到的,因为你只有一个<BaseMapLayers>元素,这是你与你的查询要找的人。添加.Elements("WMServer")方法调用,它应该工作:

from e2 in xdoc.Elements("GISImportConfig").Elements("BaseMapLayers").Elements("WMServer") 
select new 
{ 
    Url = (string)e2.Attribute("url"), 
    Enabled = (string)e2.Attribute("enabled"), 
    UserName = (string)e2.Attribute("username"), 
    Pasword = (string)e2.Attribute("password"), 
    Layers = e2.Elements("WMLayer") 
}; 

返回2个元素具有非空属性值。

0

看起来您正在尝试获取WMServer元素,并且您当前正在选择BaseMapLayers元素(其中只有一个元素存在)。

您可以通过这样得到WMServer元素:

from e2 in xdoc.Descendants("WMServer") 
select new 
{ 
     Url = (string)e2.Attribute("url"), 
     Enabled = (string)e2.Attribute("enabled"), 
     UserName = (string)e2.Attribute("username"), 
     Pasword = (string)e2.Attribute("password"), 
     Layers = e2.Elements("WMLayer") 
}; 

将抓住你所有的WMServer后代元素。

我觉得MarcinJuraszek有一个更好的答案(追加相关元素),因为如果找到错位的WMServer元素,或者只希望那些位于xml中特定位置的问题遇到问题的可能性较小。

+0

感谢您解释如何解答您的答案与MarcinJuraszek不同。它有帮助。 – will