【问题标题】:Select xml file part with xpath and xdocument - C#/Win8使用 xpath 和 xdocument 选择 xml 文件部分 - C#/Win8
【发布时间】:2013-10-11 10:35:40
【问题描述】:

我正在构建一个 Windows 8 应用程序,我需要将整个 XML 节点及其子节点作为字符串从一个大型 xml 文档中提取出来,目前执行该操作的方法如下所示:

    public string GetNodeContent(string path)
    {
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.IgnoreWhitespace = true;
        settings.ConformanceLevel = ConformanceLevel.Auto;
        settings.IgnoreComments = true;
        using (XmlReader reader = XmlReader.Create("something.xml", settings))
        {
            reader.MoveToContent();
            reader.Read();

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(reader.ReadOuterXml());
            IXmlNode node = doc.SelectSingleNode(path);

            return node.InnerText;

        }
    }

当我传递任何形式的 xpath 时,node 会得到 null 的值。我正在使用阅读器获取根节点的第一个子节点,然后使用 XMLDocument 从该 xml 创建一个。由于它是 Windows 8,显然,我不能使用 XPathSelectElements 方法,这是我想不到的唯一方法。有没有办法使用这个或任何其他逻辑来做到这一点?

提前感谢您的回答。

[更新]

假设 XML 具有以下一般形式:

<nodeone attributes...>
    <nodetwo attributes...>
        <nodethree attributes... />
        <nodethree attributes... />
        <nodethree attributes... />
    </nodetwo>
</nodeone >

当我通过“/nodeone/nodetwo”或“//nodetwo”时,我希望以xml字符串的形式得到nodetwo及其所有子节点

【问题讨论】:

  • 请提供示例 XML。您必须在路径中缺少 xml 命名空间,否则路径错误
  • 我已经编辑了问题以添加一些示例...
  • 您的输入 XML 中是否有 xmlns 声明?
  • 可以,但是不能从windows 8 store app类库调用doc.NameTable

标签: c# xml xpath windows-8


【解决方案1】:

我想出了这个解决方案,整个方法一开始就错了。有问题的部分是这段代码

reader.MoveToContent();
reader.Read();

自己忽略命名空间,因为它跳过了根标记。这是新的工作代码:

public static async Task<string> ReadFileTest(string xpath)
{
    StorageFolder folder = await Package.Current.InstalledLocation.GetFolderAsync("NameOfFolderWithXML");
    StorageFile xmlFile = await folder.GetFileAsync("filename.xml");
    XmlDocument xmldoc = await XmlDocument.LoadFromFileAsync(xmlFile);

    var nodes = doc.SelectNodes(xpath);
    XmlElement element = (XmlElement)nodes[0];

    return element.GetXml();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 2011-02-26
    • 1970-01-01
    相关资源
    最近更新 更多