【问题标题】:Xml-C# i can't set a value for the element [duplicate]Xml-C#我无法为元素设置值[重复]
【发布时间】:2015-03-11 15:50:00
【问题描述】:
XElement service = doc.Element("Ids");
service.Add(new XElement("ID", idulong.ToString(),new XElement("Succesfull",1)));

示例输出

<ID>
9223372036854775808
<Succesfull>1</Succesfull>
</ID>`

我想要

<Ids Userid= 9223372036854775808>  
<Succesfull>1</Succesfull>
</Ids>

每个用户的ID都不一样。我想检查具有ID的用户。

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:

    查看您的代码只是更改为显示嵌套级别:

    service.Add(new XElement("ID",
                             idulong.ToString(),
                             new XElement("Succesfull",
                                          1)));
    

    换句话说,Succesfull 元素在 ID 元素构造函数调用中。

    您只想添加两个单独的元素,或者通过两次单独调用service.Add

    service.Add(new XElement("ID", idulong.ToString());
    service.Add(new XElement("Succesfull", 1));
    

    或一次调用Add,获取多个元素:

    service.Add(new XElement("ID", idulong.ToString()),
                new XElement("Succesfull", 1));
    

    顺便说一句,你不需要打电话给ToString - 可以写:

    service.Add(new XElement("ID", idulong),
                new XElement("Succesfull", 1));
    

    (您可能想使用Successful 或只使用Success 而不是Succesfull...)

    【讨论】:

    • 感谢您的回答,但这不起作用,因为我尝试创建用户。此代码创建不同的元素,我想创建元素(为每个用户)并应用元素。这是我的错,我没有t 创建一个真正的问题
    • @user4126354:对不起,我完全不明白你的评论。这将创建您说想要的 XML。如果那不是实际上你想要的,你的问题应该更清楚。 “应用元素”是什么意思?
    • 哦,谢谢所有的答案。我想用 id 元素检查用户 afaik 我需要为 id 应用属性。这是真的吗?
    • @user4126354:我不明白你的意思。 花时间真正澄清你的意思。
    • @JonSkeet - 我强烈怀疑问题中显示的无效 XML &lt;Ids Userid= 9223372036854775808&gt; 旨在演示“如何创建具有 UserId 属性的元素”(看起来前段时间已经回答了 stackoverflow.com/questions/5063936/…) ...不太清楚为什么Ids 元素会有UserId 属性所以...
    【解决方案2】:

    试试这个:

    XElement service = doc.Element("Ids");
    service.Add(
        new XElement("ID", idulong.ToString()),
        new XElement("Succesfull", 1)
    );
    

    【讨论】:

    • thx 但这会创建与我的代码相同的不同元素
    • @user4126354:当你得到三个答案,没有一个是你喜欢的,所有这些都完全符合你要求的要求时,你应该想想你问得够不够清楚...
    • 正是@JonSkeet.......
    【解决方案3】:
    XElement service = doc.Element("Ids");
    service.Add(new XElement("ID", idulong.ToString()),
            new XElement("Succesfull", 1));
    

    不是

    service.Add(new XElement("ID", idulong.ToString(),new XElement("Succesfull",1)));
    

    【讨论】:

    • 这段代码在 Ids 上创建不同的元素
    猜你喜欢
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多