【问题标题】:linq to xml getting value of an attribute out of web.configlinq to xml 从 web.config 中获取属性的值
【发布时间】:2013-04-02 00:11:27
【问题描述】:

您好,我遇到了以下问题。我想使用linq 从以下代码中获取 baseLocation(D:\NewSites\TEST) 的值。 我尝试了一些东西,但它似乎不起作用。 任何想法如何做到这一点? 提前致谢。 委托人

我从这样的东西开始,但返回 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="test@gmail.com" />
        <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>

【问题讨论】:

  • LINQ to SQL 和 XML 应该如何结合在一起?请展示您的方法,以便我们为您解决问题。
  • 是的,很抱歉,那里是 XML 大类型错误。

标签: c# asp.net xml linq


【解决方案1】:

要使用 LINQ 和 C# 来提取属性,请使用类似这样的方法

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

【讨论】:

    【解决方案2】:
    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);
    

    如果您需要进一步的帮助,请告诉我,如果有帮助请标记。

    【讨论】:

      【解决方案3】:

      这个怎么样:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-10
        • 2013-02-22
        • 2013-01-10
        • 1970-01-01
        • 1970-01-01
        • 2020-08-28
        • 2013-10-27
        • 1970-01-01
        相关资源
        最近更新 更多