我是这样做的:
第一部分很简单——创建一个文档,并为根创建一个 DocumentElement(这里有一个问题,我稍后会谈到):
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmlDeclaration, root);
下一部分似乎很简单——创建一个元素,给它一个前缀、名称和 URI,然后将它附加到文档中。我认为这会起作用,但事实并非如此(这是对 XML 的最小理解发挥作用的地方):
XmlElement abcXML = xmlDoc.CreateElement("ase", "abcXML", "urn:abcXML:r38 http://www.w3.org/2001/XMLSchema-instance");
XmlAttribute xmlAttr = xmlDoc.CreateAttribute("xsi:schemaLocation", "urn:abcXML:v12 http://www.test.com/XML/schemas/v12/abcXML_v12.xsd");
abcXML.AppendChild(xmlAttr);
xmlDoc.AppendChild(abcXML);
我尝试使用doc.LoadXml() 和doc.CreateDocumentFragment() 并编写自己的声明。不 - 我会得到“文件意外结束”。对于那些对XmlDocumentFragment感兴趣的人:https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmldocumentfragment.innerxml?view=netcore-3.1
这篇关于 XML 架构和命名空间的 Microsoft 文章没有直接帮助我:https://docs.microsoft.com/en-us/dotnet/standard/data/xml/including-or-importing-xml-schemas
在阅读了更多关于 XML 的内容并浏览了 XmlDocument、XmlElement 和 XmlAttribute 的文档后,解决方案如下:
XmlElement abcXML = xmlDoc.CreateElement("ase", "abcXML", "urn:abcXML:r38");
XmlAttribute xmlAttr = xmlDoc.CreateAttribute("xsi:schemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
xmlAttr.InnerXml = "urn:abcXML:v12 http://www.test.com/XML/schemas/v12/abcXML_v12.xsd";
abcXML.Attributes.Append(xmlAttr);
xmlDoc.AppendChild(abcXML);
现在您可以像这样将元素添加到文档中:
XmlElement header = doc.CreateElement(string.Empty, "Header", string.Empty);
abcXML.AppendChild(header);
为了保存文档,我使用了:
xmlDoc.Save(fileLocation);
我将我的输出与我的样本进行了比较,在比较了文件内容之后,我成功地匹配了它。我将输出提供给客户,他们将其上传到他们正在使用的应用程序中,但失败了:Row 1, Column 1 - Unexpected Character。
我怀疑它在编码,我是对的。使用xmlDoc.Save(fileLocation) 是正确的,但它会在第1 行第1 列生成一个带有字节顺序标记(BOM) 的UTF-8 文件。应用程序中的XML 解析函数没有预料到这一点,因此该过程失败了。为了解决这个问题,我使用了以下方法:
Encoding enc = new UTF8Encoding(false); /* This creates a UTF-8 encoding without the BOM */
using (System.IO.TextWriter tw = new System.IO.StreamWriter(filePath, false, enc))
{
xmlDoc.Save(tw);
}
return true;
我再次生成文件,发送给客户端,它首先工作。
我希望有人觉得这很有用。