XDocument에 문서 유형을 추가하려면 어떻게합니까?
-
06-07-2019 - |
문제
XML DocType를 추가하려는 기존 XDocument 객체가 있습니다. 예를 들어:
XDocument doc = XDocument.Parse("<a>test</a>");
다음을 사용하여 XDocumentType를 만들 수 있습니다.
XDocumentType doctype = new XDocumentType("a", "-//TEST//", "test.dtd", "");
그러나 기존 XDocument에 어떻게 적용합니까?
해결책
당신은 추가 할 수 있습니다 XDocumentType
기존에 XDocument
, 그러나 첫 번째 요소가 추가되어야합니다. 이것을 둘러싼 문서는 모호합니다.
사용의 편리한 접근 방식을 지적 해 준 Jeroen에게 감사합니다. AddFirst
의견에서. 이 접근법은 다음 코드를 작성할 수 있습니다. 여기에는 추가 방법을 보여줍니다. XDocumentType
후 XDocument
이미 요소가 있습니다.
var doc = XDocument.Parse("<a>test</a>");
var doctype = new XDocumentType("a", "-//TEST//", "test.dtd", "");
doc.AddFirst(doctype);
또는 당신은 그것을 사용할 수 있습니다 Add
추가 방법 XDocumentType
기존에 XDocument
, 그러나 경고는 먼저 다른 요소가 존재하지 않아야한다는 것입니다.
XDocument xDocument = new XDocument();
XDocumentType documentType = new XDocumentType("Books", null, "Books.dtd", null);
xDocument.Add(documentType);
반면에, 다음은 유효하지 않으며 "이 작업은 잘못 구조화 된 문서를 생성 할 것"입니다.
xDocument.Add(new XElement("Books"));
xDocument.Add(documentType); // invalid, element added before doctype
다른 팁
그냥 전달하십시오 XDocument
건설자 (전체 예):
XDocument doc = new XDocument(
new XDocumentType("a", "-//TEST//", "test.dtd", ""),
new XElement("a", "test")
);
또는 사용 XDocument.Add
(그만큼 XDocumentType
루트 요소 앞에 추가해야합니다) :
XDocument doc = new XDocument();
doc.Add(new XDocumentType("a", "-//TEST//", "test.dtd", ""));
doc.Add(XElement.Parse("<a>test</a>"));
제휴하지 않습니다 StackOverflow