在元素中选择特定属性

时间:2014-07-12 15:33:36

标签: c# xml linq linq-to-xml

我有一个xml数据库,其中包含一些细节,但我无法获取属性的值。我正在使用XDocument - linq到xml。

我的数据库:

<?xml version="1.0" encoding="utf-8"?>
<Bundle xmlns="urn:uiosp-bundle-manifest-2.0" Name="ContactUsPlugin" SymbolicName="ContactUsPlugin" Version="1" InitializedState="Active">
  <Activator Type="ContactUsPlugin.Activator" Policy="Immediate" />
  <Runtime>
    <Assembly Path="bin\ContactUsPlugin.dll" Share="false" />
  </Runtime>

  <Functionality>
    <Controller>About</Controller>
    <View>Index</View>
  </Functionality>

  <Scripts>
    <Script version="1">
      <Location>E:\Git Projects\Kapsters\Plugins\ContactUsPlugin\Sql\Sql1.txt</Location>
    </Script>
    <Script version="2">
      <Location>E:\Git Projects\Kapsters\Plugins\ContactUsPlugin\Sql\Sql1.txt</Location>
    </Script>
  </Scripts>
</Bundle>

我正在尝试从元素Assembly中获取path属性。

我尝试了什么:

 var assemblyLocation =
            ManifestDocument.Element(ns + "Bundle").Element("Runtime").Element("Assembly").Attribute("Path").Value;

     var assemblyLocation =
            ManifestDocument.Root.Descendants("Runtime").Select(x => x.Element("Assembly").Attribute("Path").Value).First();

    var assemblyLocation =
           (from db in ManifestDocument.Root.Descendants("Runtime") select db.Element("Assembly").Attribute("Path").Value).First();

1 个答案:

答案 0 :(得分:0)

您需要在Descendants()方法中指定命名空间,否则它将只返回null:

XNamespace ns = XNamespace.Get("urn:uiosp-bundle-manifest-2.0");
XDocument ManifestDocument = XDocument.Load(@"myxml.xml");

string path;
var assemplyElement = ManifestDocument.Descendants(ns + "Assembly").FirstOrDefault();
if (assemplyElement != null)
{
    path = (string)assemplyElement.Attribute("Path");
}