0

I would like to extract data from XML and convert it to a DateTime through XPaths. I have following function:

DateTime? GetXPathDate(string xPath, XDocument xDoc)
{
    DateTime? result = null;
    var element = xDoc.XPathSelectElement(xPath);
    return result;
}

I can find the element but the issue it is wrapped in an CData:

<CarName>
    <![CDATA[XXX Jan]]>
</CarName>

Is there anyway to ignore the CData part via the XDocument or do I need to regex my self out of this?

8
  • Your example is unclear - you've shown the document, but not the xpath you expect to find the data (or even what the data is that you're looking for). Please provide a clearer, more complete example. Commented Mar 19, 2021 at 17:29
  • System.Xml.Linq already knows how to work with CDATA through XCData. You don't need to regex or anything. Commented Mar 19, 2021 at 17:35
  • To select a CData text value, see How do I retrieve element text inside CDATA markup via XPath? or How do i read individual xml nodes from a node that contains both CDATA and xml. Do those answer your question? Commented Mar 19, 2021 at 17:48
  • I tried /Root/Car/CarName/text() but thorws following: The XPath expression evaluated to unexpected type System.Xml.Linq.XCData. I saw that post but failed to succeed. Commented Mar 19, 2021 at 18:19
  • 1
    It is extremely rare that I use XPath, but when I just mocked up a sample, XElement is smart enough to provide the cdata content as the Value. So, if your xpath is correct, the string you need to parse to a date is simply element.Value Commented Mar 19, 2021 at 18:49

1 Answer 1

0

Please try the following conceptual example.

c#

void Main()
{
    string elementName = "CarName";
    
    XElement xelem = XElement.Parse("<CarName><![CDATA[XXX Jan]]></CarName>");
    
    XElement x = xelem.DescendantsAndSelf(elementName).FirstOrDefault();
    Console.WriteLine(x.Value);
}

Output

XXX Jan
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.