C#Linq XML按ElementName提取值

时间:2012-07-20 10:54:13

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

我有以下示例MODS XML部分:

<modsCollection xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-4.xsd" xmlns="http://www.loc.gov/mods/v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <mods version="3.4">
      <titleInfo>
         <title>PhD study</title> 
         <subTitle>trends and profiles 1996-97 to 2009-10</subTitle> 
      </titleInfo>
   <typeOfResource>text</typeOfResource> 
     ...
   </mods>
</modsCollection>

我的尝试:

        XNamespace ns = "http://www.loc.gov/standards/mods/v3";
        var test = modsDoc.Descendants(ns + "title").Single().Value;
        test.Should().NotBeNull();

Source Example.

上面给了我绝对没有! 'System.InvalidOperationException:序列不包含任何元素

1 个答案:

答案 0 :(得分:2)

因为您在代码中使用的NameSpace是错误的。它应该是:

XNamespace ns = "http://www.loc.gov/mods/v3";

或者如果您想避免命名空间,请尝试:

var test2 = modsDoc.Descendants().Where(a => a.Name.LocalName == "title").Single().Value;

编辑:

检查此示例:

XDocument modsDoc = XDocument.Load("test.xml");
XNamespace ns = "http://www.loc.gov/mods/v3";
var test = modsDoc.Descendants(ns + "title").Single().Value;
var test2 = modsDoc.Descendants().Where(a => a.Name.LocalName == "title").Single().Value;
Console.WriteLine(test);
Console.WriteLine(test2);

输出将是:

PhD study
PhD study