【问题标题】:Find values in a text string在文本字符串中查找值
【发布时间】:2016-11-14 22:30:47
【问题描述】:

我正在读取 XML 文件,但是这些格式不正确,所以我正在通过文本函数读取它们。我的问题是我需要从不同的标签中获取值,例如:

我需要的是最后一个标签的值,例如:15.000、9.490 和 9.220。

我阅读了文件:

public string Leer(string archivo)
{
    string texto;
    using (var streamReader = new StreamReader(archivo, Encoding.UTF8))
    {
        texto = streamReader.ReadToEnd();
    }
    return texto;
}

我读取了字符串的片段,其中包含数值:

public string getRango(string strSource, string strStart, string strEnd)
{
    int Start, End;
    if (strSource.Contains(strStart) && strSource.Contains(strEnd))
    {
        Start = strSource.IndexOf(strStart, 0) + strStart.Length;
        End = strSource.IndexOf(strEnd, Start);
        return strSource.Substring(Start, End-3500);
    }
    else
    {
        return "";
    }
}

我尝试使用正则表达式获取值,以便仅从文本中分离出数值。

public string extraerValor(string str)
{
    string patron = @"\d+(\.\d{1,3})?";
    string input = "";

    if (System.Text.RegularExpressions.Regex.IsMatch(str, patron))
    {
        input = Regex.Replace(str, "[a-zA-Z]*", string.Empty);
        return input;
    }
    else
    {
        return "Nada";
    }
}

所以,我使用 DataTable 来获取我读取的所有值:

 CartDT.Columns.Add("rango", typeof(string));
    CartDT.Columns.Add("ValorExtraido", typeof(string));
    CartDT.Columns.Add("nombreArchivo", typeof(string));

然后我读取值并发送到 gridview:

foreach (string file in Directory.EnumerateFiles(directoryPath, "*.xml"))
    {
        try
        {
            string lecturaXML = b.Leer(file);
            string nombreArchivo = Path.GetFileNameWithoutExtension(file);

            dr = CartDT.NewRow();
            dr["rango"] = b.getRango(lecturaXML, "<campoAdicional nombre=" + @"""TASA DE RECOLECCION DE BASURA", "</campoAdicional>");
            dr["ValorExtraido"] = b.extraerValor(b.getRango(lecturaXML, "<campoAdicional nombre=" + @"""TASA DE RECOLECCION DE BASURA", "</campoAdicional>").ToString());
            dr["nombreArchivo"] = nombreArchivo;


            CartDT.Rows.Add(dr);


        }
        catch (System.Xml.XmlException)//Excepcion en caso de xml mal formado
        { }

    }

    //mandar la informacion a la grilla
    gvwFacturas.DataSource = CartDT;
    gvwFacturas.DataBind();

}

这意味着,我想阅读: campoAdicional nombre="TASA DE RECOLECCION DE BASURA (WHATEVER)............ 5.490 ......(更多数据)......" 但我只想要数值(5.490)

结果如下:

而且我无法获得数值。

有什么办法可以得到吗? 拜托,我希望有人能帮助我。

最好的问候

【问题讨论】:

  • 为什么数据格式不正确?您可以尝试解析它并期待未成形的数据,但这只是要求在 hacks 之上进行 hack。
  • 你的意思是“它们没有正确形成”,显然第一个兴趣点应该是更正 xml,然后你可以查看 XDocument 或 XmlDocument 类

标签: c# asp.net .net xml parsing


【解决方案1】:

当标签格式未知时,可以使用正则表达式模式匹配。我整理了一个基本示例,但它应该能让你走上正确的道路。

using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ParsingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var matches = Regex.Matches(GetData(), "\".+?\"\\>\\d+\\.\\d+");

            foreach (Match m in matches)
            {
                var key = Regex.Match(m.Value, "\".+?\"");
                var value = Regex.Match(m.Value, "\\d+\\.\\d+");

                Console.WriteLine("Key is " + key.Value.Trim('"'));
                Console.WriteLine("Value is " + value.Value);
            }

            Console.ReadLine();
        }

        static string GetData()
        {
            return
                "<campoAdicional nombre=\"asdfasdhkjh fdsafhsdfkjh    1s     \">239.220</campoAdicional>" +
                "<campoAdicional nombre=\"asdfasdhkjh fdsafhsdfkjh    213     \">1229.220</campoAdicional>" +
                "<campoAdicional nombre=\"asdfasdhkjh fdsafhsdfkjh   fds       \">  9.220</campoAdicional>";
        }
    }
}

结果如下:

Key is asdfasdhkjh fdsafhsdfkjh    1s
Value is 239.220
Key is asdfasdhkjh fdsafhsdfkjh    213
Value is 1229.220

如果允许空格继续十进制值,您可以对模式进行轻微更改。例如。将模式更改为:"\".+?\"\>(\s+)?\d+\.\d+"

结果将是:

Key is asdfasdhkjh fdsafhsdfkjh    1s
Value is 239.220
Key is asdfasdhkjh fdsafhsdfkjh    213
Value is 1229.220
Key is asdfasdhkjh fdsafhsdfkjh   fds
Value is 9.220

【讨论】:

    【解决方案2】:

    这里的问题是你的正则表达式。如果您用以下模式替换您的模式,您可以从 MyNumber 组中获取您的号码。 <.>>(?\d.\d{3})<.>>

    【讨论】:

      【解决方案3】:

      并不是XML格式不正确,你只需要使用一种通配符搜索的形式来找到你想要的部分。

      使用 XDocument 将比逐行解析此数据可靠得多:

      var doc = XDocument.Load("Data.xml");
      var vals = from n in doc.Descendants("campAdicional") where n.Attribute("nombre").Value.ToString().StartsWith("TASA DE RECOLECCION DE BASURA") select n;
      foreach (XElement x in vals)
      {
          Debug.WriteLine(x.Value.ToString());
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-14
        • 2016-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多