简体   繁体   English

向 XElement 添加 XML 声明

[英]Add XML declaration to XElement

I created a big XML document using XElement and XAttribute.我使用 XElement 和 XAttribute 创建了一个大的 XML 文档。 I did it by adding the attributes to the elements and adding elements to elements.我通过向元素添加属性和向元素添加元素来做到这一点。

Like this:像这样:

// root node: PhysicalProperty
XElement PhysicalProperty = new XElement("PhysicalProperty");

// PhysicalProperty child element: Management
XElement Management = new XElement("Management");
XAttribute ManagementOrganizationName = new XAttribute("OrganizationName", property.Company.Name);
XAttribute ManagementManagementID = new XAttribute("ManagementID", property.Company.CompanyID);
Management.Add(ManagementOrganizationName);
Management.Add(ManagementManagementID);
PhysicalProperty.Add(Management);

My XML has a lot of elements.我的 XML 有很多元素。 However, I noticed that it did not created the xml declaration:但是,我注意到它没有创建 xml 声明:

<?xml version="1.0" encoding="UTF-8"?>

It looks like I should have created a XDocument.看起来我应该创建一个 XDocument。 How can I create the XDocument and add my root element (PhysicalProperty) to the XDocument?如何创建 XDocument 并将我的根元素 (PhysicalProperty) 添加到 XDocument? Is it possible?有可能吗?

您需要将new XDeclaration(...)传递给XDocument构造函数,然后是根元素。

You must start with an XDocument, which comes with a default declaration member with utf-8 encoding.您必须从一个 XDocument 开始,它带有一个默认的 utf-8 编码的声明成员。 If you need to, you could replace Declaration with a new instance of this.如果需要,您可以用这个的新实例替换声明。

var fi = new FileInfo(@"[MyFileName]");
var cultureName = "en-CA";
XDocument doc = XDocument.Load(fi.FullName, LoadOptions.PreserveWhitespace);
var language = doc.Descendants()
        .Where(t => t.Name.LocalName == "Language")
        .FirstOrDefault();

if (language != null && language.Value != cultureName)
{
    language.SetValue(cultureName);
    File.WriteAllText(fi.FullName
        , $"{doc.Declaration}{doc.ToString()}"
        , encoding: Encoding.UTF8);
}

From the document you can search, browse, or create items.您可以从文档中搜索、浏览或创建项目。 Once you need to store the contents of the XML document as such, with its declaration, you can simply concatenate the declaration when saving the content.一旦您需要存储 XML 文档的内容及其声明,您可以在保存内容时简单地连接声明。 The content of the document already includes a line break to incorporate the declaration.文档的内容已经包含一个换行符来合并声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM