.net - 使用 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
我究竟做错了什么 ?还是正常?
解决方案
推荐阅读
- javascript - `String.fromCharCode(event.keyCode)` 行为异常
- python - 如何在 JSON 文件中重复保存 python 输出值
- ios - 使用 UISearchBar 时的下拉菜单或弹出框
- c++ - 如何删除cPP字符串中的第二个重复字符
- powershell - 安全字符串 Powershell
- python - 发出并发和连续的作业 ID
- python - 计算 pandas 中的唯一值
- amazon-web-services - 从不同的 API 端点调用相同的 Lambda 函数
- python - 堆栈熊猫数据框
- navicat - 将 sql 文件执行到数据库时,AUTO_COMMIT=0 是什么意思?