2013-04-10 31 views
1

您好,我遇到了以下問題。我想使用linq從以下代碼中獲取baseLocation(D:\ NewSites \ TEST)的值。 我嘗試了一些東西,但它似乎沒有工作。 任何想法如何做到這一點? 在此先感謝。 Trustoslinq to xml從web.config中獲取屬性的值

我開始用這樣的事情,但這返回null

XDocument document = XDocument.Load("C:\\web.config"); 
var dataList = from item in document.Descendants("configuration") select item; 

這裏是我的XML

<?xml version="1.0"?> 
<configuration> 
    <configSections> 
    </configSections> 
    <log4net> 
    </log4net> 
    <web> 
     <website runtimeMode="Development" siteName="TEST" baseLocation="D:\NewSites\TEST"  sitePath="D:\NewSites\TEST\WebApps\Website" siteUri="http://test.co.uk" s iteEmail="[email protected]" /> 
     <cms defaultTemplate="TEST\Content.aspx" templatesUrl="/Manager/Templates/"> 
     <publishingLocations> 
      <publishingLocation name="TEST" uri="http://test.co.uk" path="WebApps\Website" /> 
     </publishingLocations> 
     <redirectables /> 
     <searchEngineSiteMapNotifications /> 
     <siteMapXmlUrls /> 
     <pingServices /> 
     <reservedTemplates /> 
     <templateFilters /> 
     </cms> 
    </web> 
    <location path="Manager"> 
    </location> 
    <connectionStrings> 
    </connectionStrings> 
    <system.web> 
    </system.web> 
</configuration> 
+0

如何是LINQ to SQL和XML應該走到一起呢?請展示您的方法,以便我們爲您解決它們。 – 2013-04-10 08:43:09

+0

是啊,我很抱歉,它是XML大型錯誤那裏。 – Trustos 2013-04-10 08:47:05

回答

2

使用LINQ和C#拉一個屬性,使用這樣的

XDocument document = Xdocument.Load("~/web.config"); 
var location = document.Descendants().Single(i=>i.Attribute("baseLocation") !=null) 
       .Attribute("baseLocation").Value; 
+1

謝謝你的伎倆。 – Trustos 2013-04-10 08:53:16

1
This will do the task: 

XmlDocument xml = new XmlDocument(); 
xml.Load(@"location of xml/config");// xml.Load(@""~/web.config"); 
XmlNode node = xml.DocumentElement.SelectSingleNode("//website"); 
Response.Write(node.Attributes["baseLocation"].Value); 

讓我知道你是否需要進一步的幫助,或者如果它幫助請注意。

0

如何:

string baseLocation = document.Descendants("website").First().Attribute("baseLocation").Value; 
+0

這工作以及感謝大家的幫助 – Trustos 2013-04-10 09:25:38