【问题标题】:How do I add a namespace prefix to XElement如何向 XElement 添加命名空间前缀
【发布时间】:2012-10-12 09:06:01
【问题描述】:

我知道http://msdn.microsoft.com/en-us/library/bb387069.aspx。我已阅读示例文章。但是在 F# 中,String 到 XName 的转换存在一些问题。我尝试使用的一些代码:

let ( !! ) : string -> XName = XName.op_Implicit


> XElement(!!"tmp:" + !!"root", !!"Content");; 
stdin(9,21): error FS0001: The type 'XName' does not support any operators named '+'

> XElement(!!("tmp:" + "root"), !!"Content");;
System.Xml.XmlException: The ':' character, hexadecimal value 0x3A, cannot be included in a name.

> XElement("tmp" + "root", "Content");;   
The type 'string' is not compatible with the type 'XName'

我想要什么:

<tmp:root>Content</tmp:root>

更新: 我只想要标签之前的前缀命名空间,就像这样:

<tmp:root>Content</tmp:root>

没有类似的东西:

> let ns = XNamespace.Get "http://tmp.com/";; 

val ns : XNamespace = http://tmp.com/

> let xe = XElement(ns + "root", "Content");;

val xe : XElement = <root xmlns="http://tmp.com/">Content</root>

【问题讨论】:

    标签: xml f#


    【解决方案1】:

    我通常做的是……

    let xmlns = XNamespace.Get
    
    let ns = xmlns "http://my.namespace/"
    
    XElement(ns + "root", "Content")
    

    此外,我倾向于不担心在字符串输出中格式化命名空间的两种不同方式之间的差异。对于 XML 解析器来说,这一切都意味着同样的事情。

    【讨论】:

    • >两种不同的命名空间格式化方式的区别 [br] 前缀 ns 和单独的 ns?我只想要前缀,我使用的不仅仅是我的 xml 格式
    • 父节点上必须存在带有 URL 和前缀定义的 xmlns 属性,然后才能创建仅具有前缀的子节点。 This question describes how to do this using LINQ to XML.
    • @JoelMueller:鉴于他特别要求提供前缀,您可能需要更新您的答案以包含该链接。
    【解决方案2】:

    我要做的是为每个命名空间定义一个额外的函数:

    let (!!) = XName.op_Implicit
    
    let tmp = 
        let ns = XNamespace.op_Implicit "www.temp.com"
        fun n -> XNamespace.op_Addition (ns, n)
    
    XElement (tmp "root", "Content")
    

    或者,您可以创建一个函数来处理名称中的“:”:

    let xn (name : String) =
        match name.IndexOf ':' with
        | -1 -> XName.op_Implicit name
        |  i -> XNamespace.op_Addition (XNamespace.Get (name.Substring (0, i)), name.Substring (i + 1))
    
    XElement (xn "tmp:test", "Content")
    

    【讨论】:

    • 这会创建一些类似“”。我想“
    【解决方案3】:

    您需要添加一个命名空间才能使其工作。 试试这样的:

    #r "System.Xml.Linq.dll";;
    open System.Xml.Linq
    
    let ns = "tmp" |> XNamespace.Get
    let ( !! ) : string -> XName = XName.op_Implicit
    
    let rt = !!("blank")
    
    let urlset = new XElement(rt,
                              new XAttribute(XNamespace.Xmlns + "tmp",ns ),
                              new XElement( ns + "root","Content"))
    

    输出:

    val urlset : XElement =
    <blank xmlns:tmp="tmp">
       <tmp:root>Content</tmp:root>
    </blank>
    

    【讨论】:

    • 好的,"let urlset = new XElement(ns + "blank","... 因为我不需要空白节点)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多