向 XElement 添加 XML 声明
Add XML declaration to XElement
我使用 XElement 和 XAttribute 创建了一个大 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 并将我的根元素 (PhysicalProperty) 添加到 XDocument?可能吗?
您需要将 new XDeclaration(...)
传递给 XDocument
构造函数,然后是您的根元素。
您必须从 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 文档的内容及其声明,您可以在保存内容时简单地连接声明。文档的内容已经包含一个换行符以合并声明。
我使用 XElement 和 XAttribute 创建了一个大 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 并将我的根元素 (PhysicalProperty) 添加到 XDocument?可能吗?
您需要将 new XDeclaration(...)
传递给 XDocument
构造函数,然后是您的根元素。
您必须从 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 文档的内容及其声明,您可以在保存内容时简单地连接声明。文档的内容已经包含一个换行符以合并声明。