2009-09-13 6 views
1

이 같은 System.Xml.Linq.XDocument에 대한 문서 타입을 만드는 :하여 XDocument에 HTML 5 DOCTYPE을 추가 (.NET)

<!DOCTYPE html > 
:

doc.AddFirst(new XDocumentType("html", null, null, null)); 

결과 저장 XML 파일로 시작

닫는 괄호 앞에 여분의 공백이 있음을 확인하십시오. 이 공간이 나타나지 않게하려면 어떻게해야합니까? 가능하면 깨끗한 방법을 원합니다 :)

답변

2

한 가지 방법은 XmlWriter를위한 래퍼 클래스를 작성하는 것입니다. 그래서 :

XmlWriter writer = new MyXmlWriterWrapper(XmlWriter.Create(..., settings)) 

그런 다음 MyXmlWriterWrapper 클래스의 WriteDocType 방법을 제외하고, 바로 포장 작가에 이르기까지 호출을 전달하는 XmlWriter를 클래스 인터페이스에 각각의 방법을 정의합니다. 그런 다음이를 다음과 같이 정의 할 수 있습니다.

public override void WriteDocType(string name, string pubid, string sysid, string subset) 
{ 
    if ((pubid == null) && (sysid == null) && (subset == null)) 
    { 
     this.wrappedWriter.WriteRaw("<!DOCTYPE HTML>"); 
    } 
    else 
    { 
     this.wrappedWriter.WriteDocType(name, pubid, sysid, subset); 
    } 
} 

분명히 솔직한 해결책은 아니지만 일을 할 것입니다.

+0

나는 지금 비슷한 것을하고있다 : 기본 TextWriter로 doctype을 수동으로 작성한 다음, XmlWriter를 사용하여 XDocument를 작성한다. 나는 더 이상 XDocumentType 객체를 추가하지 않을 것이다. –

0

틀릴 수도 있지만 HTML 이후에 예상되는 매개 변수가 더 많기 때문에이 공간이 맞다고 생각합니다. HTML5에서도 허용됩니다.

최소한 세 번째 매개 변수 (* .dtd)도 지정하십시오. 이 같은 또는 무언가 : 당신은 XmlTextWriter에 쓸 경우

new XDocumentType("html", "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd", null) 
+2

덜 복잡하기 쉬운 HTML5 doctype 사용의 이점을 무효화합니다. – hsivonen

4

당신은 공간을하지 않습니다

 XDocument doc = new XDocument(); 
     doc.AddFirst(new XDocumentType("html", null, null, null)); 
     doc.Add(new XElement("foo", "bar")); 

     using (XmlTextWriter writer = new XmlTextWriter("c:\\temp\\no_space.xml", null)) { 
      writer.Formatting = Formatting.Indented; 
      doc.WriteTo(writer); 
      writer.Flush(); 
      writer.Close(); 
     } 
+0

흥미 롭지 만 XML 선언을 생략하기 위해 Settings 속성을 설정할 수는 없습니다. XmlWriter.Create를 사용하여 설정을 전달합니다. –

+1

Reflector에서 일부 파고 들자 마자 XmlTextWriter와 XmlEncodedRawTextWriter의 WriteDocType 구현이 약간 다르게 보입니다. 이것은 여분의 공백 문자를 설명합니다. –