获得一条路径'当前XmlReader位置

时间:2015-03-13 10:40:00

标签: c# .net xml xpath

我真正喜欢Json.NET中的JsonReader,你总是知道当前JsonReader位置的路径。例如,我们有一个像这样的json:

{
    "name" :
    {
        "first": "John",
        "last": "Smith"
    }
}

如果我们站着或者约翰"元素,JsonReader.Path将是" name.first"

有没有办法实现与XmlReader类似的东西?也许使用XPath?例如,我们有一个像这样的xml:

<root>
    <name>
        <first>John/<first>
        <last>Smith</last>
    </name>
</root>

我想得到&#34; / root / name / first&#34;站在&#34; John&#34;和&#34; / root / name / last&#34;站在&#34;史密斯&#34;

2 个答案:

答案 0 :(得分:2)

似乎没有办法使用标准的.NET功能来实现这一点,所以我想出了自己的类。

internal sealed class XmlReaderWrapperWithPath : IDisposable
{
    private const string DefaultPathSeparator = ".";

    private readonly Stack<string> _previousNames = new Stack<string>();
    private readonly XmlReader _reader;
    private readonly bool _ownsReader;

    public XmlReaderWrapperWithPath(XmlReader reader, bool ownsReader)
    {
        if (reader == null)
        {
            throw new ArgumentNullException("reader");
        }

        _ownsReader = ownsReader;
        _reader = reader;
        PathSeparator = DefaultPathSeparator;
    }

    public bool Read()
    {
        var lastDepth = Depth;
        var lastName = Name;

        if (!_reader.Read())
        {
            return false;
        }

        if (Depth > lastDepth)
        {
            _previousNames.Push(lastName);
        }
        else if (Depth < lastDepth)
        {
            _previousNames.Pop();
        }

        return true;
    }

    public string Name
    {
        get
        {
            return _reader.Name;
        }
    }

    public string Value
    {
        get
        {
            return _reader.Value;
        }
    }

    private int Depth
    {
        get
        {
            return _reader.Depth;
        }
    }

    public string Path
    {
        get
        {
            return string.Join(PathSeparator, _previousNames.Reverse());
        }
    }

    public string PathSeparator { get; set; }

    #region IDisposable

    public void Dispose()
    {
        if (_ownsReader)
        {
            _reader.Dispose();
        }
    } 

    #endregion
}

请注意,此类不会形成XPath(因此没有属性路径),但这足以满足我的需求。希望这有助于某人。

答案 1 :(得分:-2)

我使用XmlDocumentXmlNode类来处理xml数据。 在这种情况下,站在节点上时,XmlNode就是x。没有这样的方法来获取节点的路径。但是这段代码就是这样做的。

        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<root>" +
                        "<name>" +
                            "<first>John</first>" +
                            "<last>Smith</last>" +
                        "</name>" +
                    "</root>");

        XmlNodeList liste = doc.FirstChild.SelectNodes("*/first");
        XmlNode x = liste[0];   //Some Node
        string path = "";
        while (!x.Name.Equals("document"))
        {
            path = x.Name + "\\" + path;
            x = x.ParentNode;
        }