我正在尝试向现有 xml 文件添加新节点。该文件定义了 xi 命名空间:
<Module xmlns:xi="http://www.w3.org/2001/XInclude" ...
并且包含节点:
<xi:include href="somefile.xml" />
这加载得很好,我可以在现有节点上进行操作,但是如果我尝试像这样添加新节点:
XmlDocumentFragment frag = doc.CreateDocumentFragment();
frag.InnerXml =
"<SomeNode SomeAttribute=\"\">" +
" <xi:include href=\"SomeFile.xml\" />" +
"</SomeNode>";
我收到“'xi'是未声明的前缀”的 XmlException
我认为片段本身无法识别名称空间是不高兴的,但我没有看到任何直观的方法来解决这个问题。
当我写这个问题时,我有一个可行的想法,并将其发布,以防它对其他人有帮助。我决定在将片段添加到文档后添加有问题的 xml:
XmlDocumentFragment frag = doc.CreateDocumentFragment();
frag.InnerXml =
"<SomeNode SomeAttribute=\"\">" +
"</SomeNode>";
XmlNode newNode = parentNode.AppendChild(frag);
newNode.InnerXml = "<xi:include href=\"SomeFile.xml\" />";
如果有人有更干净的方法来做到这一点。我很想听听它是什么。
<xi:include href="somefile.xml" />
中,
xi
是命名空间前缀。如果使用命名空间前缀,则必须声明。您必须在使用命名空间前缀
xi
的元素之上或之上添加其声明:
xmlns:xi="http://www.w3.org/2001/XInclude"
如果您
通过以某种方式组装片段来暂时设法避开错误消息,请意识到最终结果才是重要的:如果使用了命名空间但未声明,您仍然会遇到问题。
下面的代码展示了如何使用 C# 将文本 sinppet 附加到 OneNote 桌面。
你可能知道,OneNote 中的内容存储为 xml
,每个节点的前缀为
one
。因此名称空间
xmlns:one
设置在输入部分的第一行。
xmlns:one=""http://schemas.microsoft.com/office/onenote/2013/onenote""
using System;
using System.Xml;
using System.Xml.Linq;
using Append2OneNote;
using Microsoft.Office.Interop.OneNote;
class Program
{
static void Main()
{
Microsoft.Office.Interop.OneNote.Application onenoteApp = new Microsoft.Office.Interop.OneNote.Application();
string pageId = "{3ACAE6C6-53C5-0C4F-060D-3007A1428E63}{1}{E19561840189956234832620129833010512773022001}";
onenoteApp.GetPageContent(pageId, out var CurrentPageXml);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(CurrentPageXml);
XmlNode root = xmlDoc.DocumentElement;
var LastOutline = root.LastChild;
var LastOEChildren = LastOutline.LastChild;
var LastOE = LastOEChildren.LastChild;
var pageContent = "Your text content1";
string newXML = $@"
<one:OE alignment=""left"" quickStyleIndex=""1"" selected=""partial"" xmlns:one=""http://schemas.microsoft.com/office/onenote/2013/onenote"">
<one:T selected=""all""><![CDATA[{pageContent}]]></one:T>
</one:OE>";
XmlDocumentFragment xfrag = xmlDoc.CreateDocumentFragment();
xfrag.InnerXml = newXML;
LastOEChildren.AppendChild(xfrag);
onenoteApp.UpdatePageContent(xmlDoc.InnerXml);
}
}