【问题标题】:Taking the content of a line without the tags from an XML file从 XML 文件中获取不带标签的行的内容
【发布时间】:2014-02-16 06:43:42
【问题描述】:

我的程序有一个xml文件作为输入,我只想取某一行的内容,不带xml标签.. 例如:

<string> xxx </string>

我怎样才能只得到“xxx”?

【问题讨论】:

  • 不要使用正则表达式,而是使用 XPath。
  • 为什么总是正则表达式? stackoverflow.com/questions/8577060/…
  • 好的,我不会使用正则表达式 :) 我只是在检查选项..

标签: xml f#


【解决方案1】:

正如 cmets 中所述,您不应该使用正则表达式来解析 XML,因为 .NET 有更好的库可以做到这一点。下面是一个使用 LINQ to XML 的 XDocument 类型的示例:

// Reference assemblies for LINQ to XML
#r "System.Xml.dll"
#r "System.Xml.Linq.dll"

open System.Xml.Linq

// Create document with your XML data
let doc = XDocument.Parse("<string> xxx </string>")
let el name = XName.Get(name)
// Get element named 'string' and pick its value
doc.Element(el "string").Value

【讨论】:

  • 谢谢。如果我想让它取值,不管标签名是什么?有选择吗?
  • @cookya 如果是根元素,那么可以写成doc.Root.Value。否则,您需要获取Elements() 返回的第一个元素并编写类似(doc.Elements() |&gt; Seq.head).Value 的内容。
【解决方案2】:
#r "System.Xml.Linq.dll"

open System
open System.Linq
open System.Xml.Linq

let toXName s = XName.Get s

let xml = XDocument.Load @"data.xml"
let getElements elName = xml.Root.Descendants(toXName elName)

let main() = 
  (getElements "string").First().Value
  |> printfn "%s"
//  getElements "string" |> Seq.iter (fun x -> printfn "%s" x.Value)

do main()

【讨论】:

    【解决方案3】:

    如果你不使用嵌套标签,你可以使用以下(只需要获取第一组):

    <.*?>([^<]*)<.*?>
    

    但是如果你真的在你的 xml 中使用嵌套标签,你不能只通过正则表达式来获取值,它需要一个堆栈或某种列表来这样做。

    【讨论】:

    • 认真的吗?没有嵌套标签的 XML 文档?
    • 一切皆有可能,因为我们不知道他的 xml 文件的结构以及他想要完成的工作。
    • 我不会对答案投反对票,因为它在技术上是正确的。但是,它的用处几乎没有,而且 IMO,它并没有指向任何接近正确方向的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多