Recently I faced one problem while reading the value of attribute for the XElement, I have XML in following format :
<document>
<figure xmlns:xlink="http://www.w3.org/1999/xlink" id="F1" xlink:href="image#F1.1" class="figure">
<label>Fig. 1.</label>
<caption> XYZ</caption>
</figure>
</document>
I have written following code to get the value of the href attribute of figure.
XDocument _xDocument = XDocument.Load(XXXXX);
// XXXXX - specify the path here
List<XElement> imageElements = _xDocument.Descendants("Figure").ToList();
foreach (XElement imageElement in imageElements)
{
if (imageElement.Attribute("xlink:" + "href") != null)
{
string href = imageElement.Attribute("xlink:" + "href").Value;
}
}
But I end up with the following exception :
The ':' character, hexadecimal value 0x3A, cannot be included in a name.
at System.Xml.ValidateNames.ThrowInvalidName(String s, Int32 offsetStartChar, Int32 offsetBadChar)
at System.Xml.ValidateNames.ParseNCNameInternal(String s, Boolean throwOnError)
at System.Xml.XmlConvert.VerifyNCName(String name)
at System.Xml.Linq.XName..ctor(XNamespace ns, String localName)
at System.Xml.Linq.XNamespace.GetName(String localName, Int32 index, Int32 count)
at System.Xml.Linq.XNamespace.GetName(String localName)
at System.Xml.Linq.XName.Get(String expandedName)
at System.Xml.Linq.XName.op_Implicit(String expandedName)
The solution for this is to use XNamespace as below:
XNamespace xlink = "http://www.w3.org/1999/xlink";
if (imageElement.Attribute(xlink + "href") != null)
{
string href = imageElement.Attribute(xlink + "href").Value;
}
Issue resolved yipee :)
No comments:
Post a Comment