如何解析XHTML文档中的所有实体引用并将其转换为IE可以理解的普通XHTML文档? 示例XHTML:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html [
<!ENTITY D "—">
<!ENTITY o "‘">
<!ENTITY c "’">
<!ENTITY O "“">
<!ENTITY C "”">
]>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
&O; &C;
</body>
</html>
答案 0 :(得分:2)
原来这是XmlTextReader(和XmlValidatingReader)类中的一个简单选项 - “EntityHandling”。
这是一个简单的问题演示:
System.Xml.XmlTextReader textReader = new System.Xml.XmlTextReader("testin.xml");
textReader.EntityHandling = System.Xml.EntityHandling.ExpandEntities;
System.Xml.XmlDocument outputDoc = new System.Xml.XmlDocument();
outputDoc.Load(textReader);
System.Xml.XmlDocumentType docTypeIfPresent = outputDoc.DocumentType;
if (docTypeIfPresent != null)
outputDoc.RemoveChild(docTypeIfPresent);
outputDoc.Save("testout.html");
textReader.Close();
如果您不想将文档加载到内存中,则需要使用流媒体等效文件:
System.Xml.XmlTextReader textReader = new System.Xml.XmlTextReader("testin.xml");
textReader.EntityHandling = System.Xml.EntityHandling.ExpandEntities;
System.Xml.XmlTextWriter textWriter = new System.Xml.XmlTextWriter("testout.html", System.Text.Encoding.UTF8);
while (textReader.Read())
{
if (textReader.NodeType != System.Xml.XmlNodeType.DocumentType)
textWriter.WriteNode(textReader, false);
else
textReader.Skip();
}
textWriter.Close();
答案 1 :(得分:0)
xmllint可以做到这一点,因为xmllint是用C语言编写的并且是免费软件,所以很可能相对容易适应它对C#程序的作用。这是一个例子:
% cat foo.xhtml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html [
<!ENTITY D "—">
<!ENTITY o "‘">
<!ENTITY c "’">
<!ENTITY O "“">
<!ENTITY C "”">
]>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
&O; &C;
</body>
</html>
% xmllint --noent --dropdtd foo.xhtml
<?xml version="1.0" encoding="utf-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
[Plain Unicode characters that I prefer to omit because I don't know how SO handles it]
</body>
</html>