我正在尝试创建一个信息路径表单XML文件。我最初遵循的是此示例programmatically-create-infopath-form-console-app,但遇到多个名称空间问题。
我的信息路径表单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文件
解决这个问题的正确方法是什么?
答案 0 :(得分:0)
我会使用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");
}
}
}