简体   繁体   中英

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:

    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. I'm using the reader to get the first child of root node, and then use XMLDocument to create one from that xml. Since it's Windows 8, apparently, I can't use XPathSelectElements method and this is the only way I can't think of. 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:

<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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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