【问题标题】:Will this XML parsing work?这种 XML 解析会起作用吗?
【发布时间】:2011-03-30 13:03:49
【问题描述】:
public Envio(int id)
{
    XDocument xml = XDocument.Parse(LoadFromService(id));
    ID = xml.Element("envio")
            .Element("de").Value;

    De = xml.Element("envio")
            .Element("de").Value;

    Para = xml.Element("envio")
            .Element("para").Value;

    Fecha = xml.Element("envio")
            .Element("fecha").Value;

    Descripcion = xml.Element("envio")
            .Element("descripcion").Value;
}



/*
    * <xml>
    *  <envio id="123">
    *      <de>Sergio</de>
    *      <para>Gabriela</para>
    *      <fecha>10/10/2010</fecha>
    *      <descripcion>Una moto de 30kg.</descripcion>
    *  </envio>
    * </xml>
    */

我想提取所有信息以及根标签Envio的ID属性。

有什么帮助吗?

【问题讨论】:

    标签: c# linq linq-to-xml xml-parsing


    【解决方案1】:

    您的xml 变量是一个包含单个&lt;xml&gt; 标记的XDocument 对象。

    因此,xml.Element("envio") 为空。

    相反,您需要写xml.Root.Element("envio")

    【讨论】:

      【解决方案2】:

      好吧,你似乎没有对属性 (id) 做任何事情。

      还有;与 .Value 相比,cast 是首选,因为它将通过返回 null 来处理丢失的数据。

      SomeProp = (string)node.Element("foo");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多