IbrarMumtaz
IbrarMumtaz

Reputation: 4413

C# Linq XML Extract Value By ElementName

I have the following sample MODS XML section:

<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>

My Attempt:

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

Source Example.

The above gives me absolutely nothing! 'System.InvalidOperationException: Sequence contains no elements'

Upvotes: 0

Views: 139

Answers (1)

Habib
Habib

Reputation: 223422

Because your NameSpace you are using in your code is wrong. It should be:

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

or if you want to avoid Namespace then try:

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

Edit:

Check this example:

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);

Output would be:

PhD study
PhD study

Upvotes: 2

Related Questions