Darthchai
Darthchai

Reputation: 755

How to query with XPathSelectElement

I have the following type of XML that contains a large number of DocType values:

<InvalidDocTypes>
  <DocType>DocType1</DocType>
  <DocType>DocType2</DocType>
</InvalidDocTypes>

I am trying to query the XML for the specific doc type using the following:

document.PriorDocumentType = "DocType1"
var node = doc.XPathSelectElement("//InvalidDocTypes[DocType='" + document.PriorDocumentType + "']");

I am only expecting node to be null when there is no value in the XML, but I am always getting just a null. Would it be better to use a Linq query against the XML, or what am I doing wrong with the XPathSelectElement. Any help would be appreciated. Thanks

Upvotes: 0

Views: 1033

Answers (1)

Damian
Damian

Reputation: 2852

I tested your code and it seems to be working - please verify the console application below. It prints the whole InvalidDocTypes element when DocType exists and null when it does not exist:

using System;
using System.Xml.Linq;
using System.Xml.XPath;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            var xml = @"<InvalidDocTypes>
  <DocType>DocType1</DocType>
  <DocType>DocType2</DocType>
</InvalidDocTypes>";

            var documentType = "DocType1";

            var xmlDocument = XDocument.Parse(xml);
            var node = xmlDocument.XPathSelectElement("//InvalidDocTypes[DocType='" + documentType + "']");
            Console.WriteLine(node);
        }
    }
}

Upvotes: 1

Related Questions