提问者:小点点

将XML声明添加到XElement


我使用XElement和XAt和创建了一个大的XML文档。我通过向元素添加属性和向元素添加元素来做到这一点。

像这样:

// 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);

我的XML有很多元素。但是,我注意到它没有创建xml声明:

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

看起来我应该创建一个XDocument。如何创建XDocument并将我的根元素(物理属性)添加到XDocument?可能吗?


共2个答案

匿名用户

您需要向XDocument构造函数传递一个new X声明(…),后跟您的根元素。

匿名用户

您必须从XDocument开始,它带有一个带有utf-8编码的默认声明成员。如果需要,您可以用一个新的实例替换声明。

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);
}

您可以从文档中搜索、浏览或创建项目。一旦您需要存储XML文档的内容及其声明,您可以在保存内容时简单地连接声明。文档的内容已经包含一个换行符以合并声明。