c# - 如何找到字符串格式错误的 XML(在 C# 中)的位置?

标签 c# xml algorithm

我正在编写一个轻量级的 XML 编辑器,如果用户的输入格式不正确,我想向用户指出问题所在,或者至少是第一个问题所在。有谁知道现有的算法吗?如果查看代码有帮助,如果我可以填写 FindIndexOfInvalidXml 方法(或类似方法),这将回答我的问题。

using System;

namespace TempConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "<?xml version=\"1.0\"?><tag1><tag2>Some text.</taagg2></tag1>";
            int index = FindIndexOfInvalidXml(text);
            Console.WriteLine(index);
        }

        private static int FindIndexOfInvalidXml(string theString)
        {
            int index = -1;

            //Some logic

            return index;
        }
    }
}

最佳答案

我可能只是作弊。 :) 这将为您提供行号和位置:

string s = "<?xml version=\"1.0\"?><tag1><tag2>Some text.</taagg2></tag1>";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

try
{
    doc.LoadXml(s);
}
catch(System.Xml.XmlException ex)
{
    MessageBox.Show(ex.LineNumber.ToString());
    MessageBox.Show(ex.LinePosition.ToString());
}

关于c# - 如何找到字符串格式错误的 XML(在 C# 中)的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/199238/

相关文章:

c# - WPF 进度条 PowerShell

c# - CaSTLe ActiveRecord - 总是更新 child ,为什么?

c# - Http MultipartFormDataContent

java - java中解析xml字符串

c++ - 用于替换 map vector 的外部存储器数据结构

algorithm - Splay Trees中节点的插入和删除

python - 检查列表是否包含另一个列表中的所有项目

c# - 专注于一个程序并在 C# 中做一些事情

android - 使用 getwindow() 调整背景

xml - 是否可以在 XSD 中重命名基本类型