Linq-to-XML does not receive content of node containing html tags
I have an XML file that I am trying to parse with Linq-to-XML. One of the nodes contains a bit of HTML that I cannot extract.
XML reminds:
<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<image><img src="/Images/m1cznk4a6fh7.jpg" /></image>
<contentType>Banner</contentType>
</root>
The code:
XDocument document = XDocument.Parse(content.XML);
XElement imageElement = document.Descendants("image").SingleOrDefault();
image = imageElement.Value; // Doesn't get the content, while if I specify .Descendants("contentType") it works
Any ideas?
a source to share
.Value
means any text in a tag and any child tags, but you don't have it. When you parsed it, it was <img/>
treated as a non HTML specific XML tag (Linq doesn't know the difference). For example, if your XML was written like:
<image>
<img>/Images/m1cznk4a6fh7.jpg
</img>
</image>
Then your code will work.
You will need to go further in your tens to the tag <img/>
and then get the .Value
attribute src
to extract the text you want.
a source to share
If you are going to store HTML inside XML elements, it must be inside a comment <![CDATA[]]>
, so LINQ2XML should not treat it as additional XML markup.
<image><![CDATA[<img src="Images/abc.jpg />]]></image>
If memory is used, you don't need to do anything special to retrieve the value without a CDATA comment, but you may need to call a property other than Value
. I don't quite remember.
a source to share
This is because there Value
is no Value
nested under Image
just another element ( img
). You will need to do something like:
XElement imgElement = document.Descendants("image").SingleOrDefault().FirstNode;
Then enter the property Value
to get src
. Otherwise, if you are looking for the tag img
as plain text, you will need to store it in your XML document as a CDATA section e..g
<image><![CDATA[<img src="/Images/m1cznk4a6fh7.jpg" />]]></image>
a source to share