XML 使用具有命名空间和前缀的 XmlWriter 在 c# 中的文件格式

XML file format in c# using XmlWriter having namespace and prefixes

这是我正在寻找的必需 XML 格式:

<mf:package 
 xmlns="urn:x-lexisnexis:content:manifest:global:1"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="urn:x-lexisnexis:content:manifest:global:1 sch_manifest.xsd"
 mf:mf="urn:x-lexisnexis:content:manifest:global:1">

我得到的是:

<mf:package 
 xmlns="urn:x-lexisnexis:content:manifest:global:1"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="urn:x-lexisnexis:content:manifest:global:1 sch_manifest.xsd" 
 xmlns:mf="urn:x-lexisnexis:content:manifest:global:1">

我使用的代码是:

using (XmlWriter writer = XmlWriter.Create(parentPathPackage + packageID + "_man.xml", settings))
{
    writer.WriteStartElement("mf", "package", "urn:x-lexisnexis:content:manifest:global:1");
    writer.WriteAttributeString("", "xmlns", null, "urn:x-lexisnexis:content:manifest:global:1");
    writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
    writer.WriteAttributeString("xsi", "schemaLocation", null, "urn:x-lexisnexis:content:manifest:global:1 sch_manifest.xsd");

我做错了什么?

假设您正在编写 root XML element,您想要的 XML 格式不正确:

<mf:package 
   xmlns="urn:x-lexisnexis:content:manifest:global:1" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="urn:x-lexisnexis:content:manifest:global:1 sch_manifest.xsd" 
   mf:mf="urn:x-lexisnexis:content:manifest:global:1"> <!--mf:mf is not correct -->

上传到https://www.xmlvalidation.com/会报错,

Errors in the XML document: 1: 250 The prefix "mf" for element "mf:package" is not bound.

具体来说,您定义了一个元素 <mf:package ... 但从不将 mf 前缀与名称空间相关联。 mf:mf="..." 不是正确的方法。相反,命名空间声明属性 must either be xmlns or begin with xmlns:,因此 xmlns:mf="..." 正确的方式:

<mf:package 
   xmlns="urn:x-lexisnexis:content:manifest:global:1" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="urn:x-lexisnexis:content:manifest:global:1 sch_manifest.xsd" 
   xmlns:mf="urn:x-lexisnexis:content:manifest:global:1">  <!--Corrected -->

因为这是您实际得到的 XML,XmlWriter 会自动为您生成格式正确的 XML。