xml - 当文件具有 xmlns 属性时在 F# 中解析 xml

标签 xml f# xml-namespaces

所以我尝试使用F# XML parsing post在以下 xml 中(来自 uclassify API):

<?xml version="1.0" encoding="UTF-8" ?> 
<uclassify xmlns="http://api.uclassify.com/1/ResponseSchema" version="1.01"> 
    <status success="true" statusCode="2000"/> 
    <readCalls> 
    <classify id="cls1"> 
        <classification textCoverage="1"> 
            <class className="happy" p="0.912929"/> 
            <class className="upset" p="0.0870707"/> 
        </classification> 
    </classify> 
    </readCalls> 
</uclassify>

代码是这样的:

let doc  = 
    Xdocument.Load file
doc.Element(xn "uclassify")
   .Element(xn "readCalls")
   .Element(xn "classify")
   .Element(xn "classification")
   .Element(xn "class").Attribute(xn "p")

这行不通!!!似乎无法完成解析。然而,删除属性 xmlns="http://api.uclassify.com/1/ResponseSchema"version="1.01" 使其工作:

let doc  = 
    Xdocument.Load file
    let test = IO.File.ReadAllText(file).Replace("xmlns=\"http://api.uclassify.com/1/ResponseSchema\" version=\"1.01\"","")
    XDocument.Parse(test)

doc.Element(xn "uclassify")
   .Element(xn "readCalls")
   .Element(xn "classify")
   .Element(xn "classification")
   .Element(xn "class").Attribute(xn "p")

注意这个问题似乎与 Why must I remove xmlns attribute ... 有关.所以问题是为什么我必须删除 xmlns 属性?我应该使用什么来解析具有 xmlns 属性的 xml?

谢谢

最佳答案

@dahlbyk 的版本有效,但是一旦您拥有 XNamespace 对象,就可以像在 C# 中一样在 F# 中向其添加字符串。因此,我更喜欢这种语法,因为它更接近于通常在 C# 中完成的方式:

let xn = XName.Get
let xmlns = XNamespace.Get

let ns = xmlns "http://api.uclassify.com/1/ResponseSchema"

doc.Element(ns + "uclassify")
   .Element(ns + "readCalls")
   .Element(ns + "classify")
   .Element(ns + "classification")
   .Element(ns + "class")
   .Attribute(xn "p")

关于xml - 当文件具有 xmlns 属性时在 F# 中解析 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5869898/

相关文章:

xml - XPath 如何处理 XML 命名空间?

xml - 具有同名节点的 xml 的 XSLT 转换

F# 交互式 session 持久性和其他此类用户问题

generics - f# 可区分联合泛型

F# - 反向管道顺序

xml - XPath 如何以 namespace 未知的方式识别谓词中的属性

.net - XmlnsDefinition似乎不起作用

android - Material 组件底部导航 View

c# - 反序列化字符串 XML 并出现错误 :There is an error in XML document (1, 2)

php - 如何在 PHP 中解析大型 XML 文件?