كيف يمكنني إضافة نوع المستند إلى XDocument؟
-
06-07-2019 - |
سؤال
ولدي كائن XDocument القائمة التي أود أن إضافة نوع المستند XML ل. على سبيل المثال:
XDocument doc = XDocument.Parse("<a>test</a>");
وأنا يمكن إنشاء XDocumentType باستخدام:
XDocumentType doctype = new XDocumentType("a", "-//TEST//", "test.dtd", "");
ولكن كيف تطبق ذلك إلى XDocument الحالية؟
المحلول
ويمكنك إضافة XDocumentType
إلى XDocument
القائمة، لكن يجب أن يكون بإضافة العنصر الأول. الوثائق التي تحيط بهذه غامضة.
وبفضل يروين لافتا النهج مريحة للاستخدام 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);
وعلى صعيد آخر، وفيما يلي غير صالح، وسوف يؤدي إلى InvalidOperationException: "أن هذه العملية تخلق وثيقة منظم بشكل غير صحيح"
xDocument.Add(new XElement("Books"));
xDocument.Add(documentType); // invalid, element added before doctype
نصائح أخرى
ومجرد تمريرها إلى XDocument
منشئ (<أ href ل = "http://msdn.microsoft.com/en-us/library/bb299381.aspx" يختلط = "نوفولو noreferrer"> مثال كامل ):
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>"));