【问题标题】:How to get the character location of a XmlElement?如何获取 XmlElement 的字符位置?
【发布时间】:2011-09-10 12:31:41
【问题描述】:

假设在我的 C# 代码中,我从 XmlDocument(或 XDocument强>)。如何在 XML 文件中获取此 XmlElement 的字符位置

换句话说,我想被告知

"Your element starts on the 176th character in the text file containing the XML", 

不是

"Your 'book' element is the 3rd 'book' element in the whole XML document".

【问题讨论】:

    标签: c# xml location character


    【解决方案1】:

    我不确定这是否可以确定字符数,但您可以在行内找到行号和位置:

    var document = XDocument.Load(fileName, LoadOptions.SetLineInfo);
    var element = document.Descendants("nodeName").FirstOrDefault();
    var xmlLineInfo = (IXmlLineInfo)element;
    Console.WriteLine("Line: {0}, Position: {1}", xmlLineInfo.LineNumber, xmlLineInfo.LinePosition);
    

    【讨论】:

    • 您还必须考虑到空格也很可能被忽略。这可能是你能得到的最好的了。
    • @Xaisoft - 不,空格不会被忽略。
    • 您还需要设置SetLineInfo选项以加载文档。否则行和位置值始终为 0。(使用 .NET 4.7.2 测试;可能 9 年前有所不同) var document = XDocument.Load(fileName, LoadOptions.PreserveWhitespace | LoadOptions.SetLineInfo);
    猜你喜欢
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多