繁体   English   中英

使用xpath和xdocument选择xml文件部分-C#/ Win8

[英]Select xml file part with xpath and xdocument - C#/Win8

我正在构建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及其所有子级的结果。

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

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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM