简体   繁体   English

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

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

I am building a Windows 8 app, and I need to extract the whole XML node and its children as string from a large xml document, and the method that does that so far looks like this: 我正在构建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;

        }
    }

When I pass any form of xpath, node gets the value of null. 当我传递任何形式的xpath时,node会得到null值。 I'm using the reader to get the first child of root node, and then use XMLDocument to create one from that xml. 我正在使用阅读器获取根节点的第一个子节点,然后使用XMLDocument从该xml创建一个子节点。 Since it's Windows 8, apparently, I can't use XPathSelectElements method and this is the only way I can't think of. 既然是Windows 8,显然我不能使用XPathSelectElements方法,这是我无法想到的唯一方法。 Is there a way to do it using this, or any other logic? 有没有办法使用此逻辑或任何其他逻辑来做到这一点?

Thank you in advance for your answers. 预先感谢您的回答。

[UPDATE] [更新]

Let's say XML has this general form: 假设XML具有以下一般形式:

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

I expect to get as a result nodetwo and all of its children in the form of xml string when i pass "/nodeone/nodetwo" or "//nodetwo" 当我通过“ / nodeone / nodetwo”或“ // nodetwo”时,我期望得到以XML字符串形式的nodetwo及其所有子级的结果。

I've come up with this solution, the whole approach was wrong to start with. 我想出了这个解决方案,整个方法从一开始就是错误的。 The problematic part was the fact that this code 有问题的部分是该代码

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

ignores the namespace by itself, because it skips the root tag. 它本身会忽略名称空间,因为它会跳过根标记。 This is the new, working code: 这是新的工作代码:

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