【问题标题】:Get the value between <> with dynamic number inside it获取 <> 之间的值,其中包含动态数字
【发布时间】:2015-12-24 09:10:06
【问题描述】:

我正在研究一种文本摘要方法,为了测试我的方法,我有一个名为 doc 2007 的基准,在这个基准中我有很多 xml 文件,我应该清除那个文件。

例如,我有一个像这样的xml 文件:

<sentence id='s0'>
 The nature of the proceeding 

1 The principal issue in this proceeding is whether the Victorian Arts Centre falls within the category of 'premises of State Government Departments and Instrumentalities', for the purposes of provisions in industrial awards relating to rates of payment for persons employed in cleaning those premises.</sentence>

<sentence id='s1'>In turn, this depends upon whether the Victorian Arts Centre Trust, a statutory corporation established by the Victorian Arts Centre Act 1979 (Vic) ('the VAC Act'), is properly described as a State Government department or instrumentality, for the purposes of the award provisions.</sentence>
;

我应该提取&lt;sentence id='s0'&gt;&lt;/sentence&gt;&lt;sentence id='s1'&gt;&lt;/sentence&gt;之间的字符串我的意思是结果应该是这样的:

The nature of the proceeding 

     1 The principal issue in this proceeding is whether the Victorian Arts Centre falls within the category of 'premises of State Government Departments and Instrumentalities', for the purposes of provisions in industrial awards relating to rates of payment for persons employed in cleaning those premises.

In turn, this depends upon whether the Victorian Arts Centre Trust, a statutory corporation established by the Victorian Arts Centre Act 1979 (Vic) ('the VAC Act'), is properly described as a State Government department or instrumentality, for the purposes of the award provisions.

我发现了一些类似的东西:

Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value

使用Regex,但它不起作用。你能给我一个快速的解决方案吗?

【问题讨论】:

  • 你有一个很好格式的XML,你为什么要使用正则表达式来解析它?使用 XML 解析器!
  • 我对xml解析器不熟悉
  • XML 处理是自 v1 以来 .NET 的基础部分。您可以使用旧的 XMLDocument、新的 XDocument、XPath 查询等。您甚至可以在数据表中加载 XML 文档。 Web 服务(ASMX 或 WCF)。如果不了解可用的 XML 类,就无法在 .NET 中编程。另一方面,正则表达式不适合 XML 解析,除了一些非常简单的情况。

标签: c# regex string match


【解决方案1】:

使用 LINQ to XML 应该更容易:

var res = XElement.Parse(xml)
                  .Descendants("sentence").Where(e => e.Attribute("id").Value == "s0")
                  .FirstOrDefault().Value;

或者,正如 Yeldar 所建议的,更简洁的方法是:

var s0 = XElement.Parse(xml)
                 .Descendants("sentence").FirstOrDefault(e => e.Attribute("id").Value == "s0")
                 .Value;

【讨论】:

  • 第二句应该包含
  • 你的答案只是提取第一个
  • 可以简单地用.FirstOrDefault(e =&gt; e.Attribute("id").Value == "s0") 代替.FirstOrDefault(e =&gt; e.Attribute("id").Value == "s0") :)
  • 我收到了这个错误:有多个根元素。第 5 行,位置 2。亲爱的朋友
  • @EhsanAkbar 很可能有多个根元素 :) 格式良好的 XML 文件应该只包含一个根元素。
【解决方案2】:

XElment.Parse 仅在具有单个根节点的字符串中使用。你写的实例有两个节点''没有一个根节点。 您可以添加一个根节点,如下所示:

xml = "<root>" + xml + "</root>";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2017-10-18
    相关资源
    最近更新 更多