XML에서 모든 엔티티 참조를 해결하고 C#에서 새 XML을 만드는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/614067

  •  03-07-2019
  •  | 
  •  

문제

XHTML 문서의 모든 엔티티 참조를 어떻게 해결하고 IE를 이해할 수있는 일반 XHTML 문서로 변환 할 수 있습니까? 예제 xhtml :

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html [
    <!ENTITY D "&#x2014;">
    <!ENTITY o "&#x2018;">
    <!ENTITY c "&#x2019;">
    <!ENTITY O "&#x201C;">
    <!ENTITY C "&#x201D;">
]>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    </head>
    <body>
        &O; &C;
    </body>
</html>
도움이 되었습니까?

해결책

이것은 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();

다른 팁

xmllint 이를 수행 할 수 있으며 Xmllint는 C로 작성되었으며 무료 소프트웨어이므로 C# 프로그램에 수행하는 방식을 비교적 쉽게 조정할 수 있습니다. 예는 다음과 같습니다.

% cat foo.xhtml 
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html [
    <!ENTITY D "&#x2014;">
    <!ENTITY o "&#x2018;">
    <!ENTITY c "&#x2019;">
    <!ENTITY O "&#x201C;">
    <!ENTITY C "&#x201D;">
]>
<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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top