c# - 使用 XmlTextWriter 设置多个命名空间
问题描述
我正在尝试创建一个 infopath 表单 XML 文件。我最初是以编程方式创建信息路径表单控制台应用程序的示例,但我遇到了多个命名空间的问题。
这是我的信息路径表单 XML 文件中的一些命名空间
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls"
xmlns:dms="http://schemas.microsoft.com/office/2009/documentManagement/types"
在大多数情况下,当我按照示例进行操作时,一切都很顺利,直到我阅读了 XML 文件的人员选择器部分。
我想要的是:
<my:Updated_By>
<pc:Person>
<pc:DisplayName></pc:DisplayName>
<pc:AccountId></pc:AccountId>
<pc:AccountType></pc:AccountType>
</pc:Person>
</my:Updated_By>
我做了什么(1):
string myNamespace = "http://schemas.microsoft.com/office/infopath/2003/myXSD/2007-09-02T01:11:44";
...
writer.WriteStartElement("my", "myFields", myNamespace);
writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xmlns", "pc", null, "http://schemas.microsoft.com/office/infopath/2007/PartnerControls");
...
writer.WriteStartElement("my", "Updated_By", myNamespace);
writer.WriteStartElement("pc", "Person");
writer.WriteEndElement();
writer.WriteStartElement("pc", "DisplayName");
writer.WriteEndElement();
writer.WriteStartElement("pc", "AccountId");
writer.WriteEndElement();
writer.WriteStartElement("pc", "AccountType");
writer.WriteEndElement();
writer.WriteEndElement();
...
我得到了什么(1):
<my:Updated_By>
<pc xmlns="Person" />
<pc xmlns="DisplayName" />
<pc xmlns="AccountId" />
<pc xmlns="AccountType" />
</my:Updated_By>
我不确定“xmlns=”是否对 XML 文件有任何影响,但我希望它看起来尽可能接近 infopath 生成的 XML 文件
解决这个问题的正确方法是什么?
解决方案
我会使用 Xml Linq。请参阅下面的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<my:Updated_By xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns:pc=\"http://schemas.microsoft.com/office/infopath/2007/PartnerControls\"" +
" xmlns:dms=\"http://schemas.microsoft.com/office/2009/documentManagement/types\"" +
" xmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD/2007-09-02T01:11:44\">" +
"</my:Updated_By>";
XDocument doc = XDocument.Parse(header);
XElement root = doc.Root;
XNamespace pcNs = root.GetNamespaceOfPrefix("pc");
string name = "John";
string id = "123";
string type = "person";
root.Add(new XElement(pcNs + "Person",
new XElement(pcNs + "DisplayName", name),
new XElement(pcNs + "AccountId", id),
new XElement(pcNs + "AccountType", type)
));
doc.Save("filename");
}
}
}
推荐阅读
- nlp - Spacy 手动下载 en_core_web_lg
- python - 为什么 cecond 版本比第一个版本更快地求和数组的元素?
- node.js - Heroku Node.js 机器人部署失败
- angular - 同一张表中数据的级联下拉
- bash - 运行 bash 脚本时在双引号内保留单引号
- bootstrap-4 - 创建一个 Bootstrap 轮播,显示上一张和下一张图像的预览并处理横向和纵向照片
- c++ - 如何修复“格式不是字符串文字且没有格式参数”错误?
- python - 从子字符串中提取文件名
- flutter - 在flutter web中分享来自url的图像
- php - 选择所有左表列和特定右表列时在 PHP 中输出 MySQL 左连接