首页 > 解决方案 > 使用 xml 阅读器捕获文件中的元素位置。抵消问题

问题描述

我正在尝试捕获 xml 文件中的元素位置(以构建索引)。但是我遇到了一些偏移问题,linePosition 向右移动(有时移动 2,有时移动 3)。

这是一个示例代码和一个 .netfiddle 来呈现问题

https://dotnetfiddle.net/8byHGW

using System;
using System.IO;
using System.Xml;

namespace IXmlLineInfoTests
{
    class Program
    {
        public static string Xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><snapshot><offrdefs><offrdef></offrdef></offrdefs><offers><offer></offer></offers></snapshot>";
        static void Main(string[] args)
        {
            using (StringReader sr = new StringReader(Xml))
            {
                using (XmlReader xr = XmlReader.Create(sr))
                {
                    IXmlLineInfo xli = (IXmlLineInfo)xr;
                    var startLinePosition = 0;
                    startLinePosition = xli.LinePosition;
                    Console.WriteLine($"before reading: {startLinePosition}");
                    while (xr.Read())
                    {
                        startLinePosition = xli.LinePosition;
                        if (xr.NodeType == XmlNodeType.XmlDeclaration)
                        {
                            Console.WriteLine($"declaration: {startLinePosition}");
                        }
                        else if (xr.NodeType == XmlNodeType.Element)
                        {

                            if (xr.Name == "offer")
                            {
                                Console.WriteLine($"offer: {startLinePosition}");
                            }
                            else if (xr.Name == "snapshot")
                            {
                                Console.WriteLine($"snapshot: {startLinePosition}");
                            }
                            else if (xr.Name == "offrdefs")
                            {
                                Console.WriteLine($"offrdefs: {startLinePosition}");
                            }
                        }
                    }
                }
            }
        }
    }
}

输出是

before reading: 0
declaration: 3
snapshot: 41
offrdefs: 51
offer: 99

我期待有这个

before reading: 0
declaration: 0
snapshot: 39
offrdefs: 50
offer: 98

我究竟做错了什么 ?还是正常?

标签: .netxml

解决方案


推荐阅读