c# - 阅读下面的 xml 显示 c# 中的错误

标签 c# xml office-interop

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <w:document xmlns:ve="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml">
    <w:body>
      <w:customXml w:uri="Sample" w:element="note">
        <w:p w:rsidR="00B06944" w:rsidRDefault="0051608D" w:rsidP="000E0B9F">
          <w:customXml w:element="to">
            <w:r w:rsidR="000E0B9F" w:rsidRPr="00B84BAE">
              <w:rPr>
                <w:b/>
                <w:bCs/>
              </w:rPr>
              <w:t xml:space="preserve">Saran </w:t>
            </w:r>
          </w:customXml>
        </w:body>
     </w:document>

因为我想读取节点 为此,我正在编写以下代码

XmlDocument doc = new XmlDocument();
doc.Load("\\document.xml");
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);
XmlNode node = doc.SelectSingleNode("/w:body/w:customXml/w:r", namespaceManager);

给出:

The error shown in this line is Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.

我如何读取Xml

最佳答案

您需要将别名w 的含义告知namespaceManager听起来这是多余的(来自文件),但并非如此您要查询的别名必然来自来源,因为如果我用 foo 替换源文档中的所有 w 别名(只要我也将 foo:xmlns 定义为相同)。或者我可以在整个过程中使用 xmlns 而不是别名。

因此:

XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);
namespaceManager.Add("w",
    "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
XmlNode node = doc.SelectSingleNode("/w:body/w:customXml/w:r", namespaceManager);

这允许您的查询以同样的方式成功,而不管源中使用的特定别名。

关于c# - 阅读下面的 xml 显示 c# 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8558795/

相关文章:

c# - 具有订阅者缓存的 WCF Pub/Sub

c# - 使用 SqlCommand 执行存储过程时如何防止超时错误?

c# - 在文本框上显示建议

c# - 在 IIS 中发布后未呈现 BundleConfig

c# - 如何将所有者窗口传递给 Show() 方法重载?

c# - 如何专注于刚刚通过互操作打开的 Word 文档?

使用 Aeris Weather SDK 的 java.lang.ClassNotFoundException : com. hamweather.aeris.maps.R$layout

java - Spring 3.0 : "The prefix" X "for attribute" Y "associated with an element type" Z "is not bound"

java - 如何使用简单 Xml 框架反序列化表示根级数组的 xml

c# - 从 Open Xml 文档创建 Microsoft Word Interop 文档