Linq to Xml and custom xml entities
Question
I want to create a MathML document from an expression tree using Linq to xml, but I cannot figure out how to use the MathML xml entities (such as and &InvisibleTimes): When I try to create directly a XElement using
XElement xe = new XElement("mo", "&InvisibleTimes");
it justs escapes the ampersand (which is no good). I also tried to use XElement.Parse
XElement xe = new XElement.Parse("<mo>&InvisibleTimes</mo>");
but it fails with an System.XmlException: Reference to undeclared entity 'InvisibleTimes' How can I declare the entity or ignore the checks?
Solution
As others have pointed out, there is no direct way to do it.
That said, you can try using the corresponding unicode caracther. According to http://www.w3.org/TR/MathML2/mmlalias.html, for ApplyFunction it is 02061, try new XElement("mo", "\u02061")
OTHER TIPS
According to this thread, LINQ to XML doesn't include entity references: it doesn't have any node type for them. It just expands them as it loads a file, and after that you've just got "normal" characters.
I don't know about XDocument
, but you can do it with XmlDocument
:
XmlDocument doc = new XmlDocument();
var entity = doc.CreateEntityReference("InvisibleTimes");
XmlElement root = (XmlElement)doc.AppendChild(doc.CreateElement("xml"));
var el = root.AppendChild(doc.CreateElement("mo")).AppendChild(entity);
string s = doc.OuterXml;
You may need to xml encode the names because '&' is a special character.
So instead of
XElement xe = new XElement("mo", "&InvisibleTimes");
try
XElement xe = new XElement("mo", "&InvisibleTimes");
I think you'll need a DTD to define <mo></mo>.
MathML 2.0 provides an XHTML + MathML DTD.
A workaround is to use any placeholder for the & such as ;_amp_;
XElement xe = new XElement("mo", ";_amp_;InvisibleTimes)
and restore it when you get the xml string:
output = xe.ToString().Replace(";_amp_;", "&")