how to add self-closing tag to an element in xml?

倾然丶 夕夏残阳落幕 提交于 2020-06-17 04:12:22

问题


There are plenty of information for how to avoid self-closing tag for an XElement in C# on the web, but I want to do is the reverse one. I give a value to an XElement, and also want to see a self-closing tag in the output xml.

This is my code:

XElement myElement = new XElement("MyItem",
    new Attribute("value1", "test1),
    new Attribute("value2", "test2),
    new Attribute("value3", "test3)
);

This is what I got now in the output xml file:

<MyItem value1="test1" value2="test2" value3="test3">

</MyItem>

What I want is:

<MyItem value1="test1" value2="test2" value3="test3" />

How to do it? Thanks.

Additional information:

I am using C# with Visual Studio 2012.


回答1:


It is unclear what is the problem here. Your code (after some minor fixes) produces self-closing tag for me :

XElement myElement = new XElement("MyItem",
                                  new XAttribute("value1", "test1"),
                                  new XAttribute("value2", "test2"),
                                  new XAttribute("value3", "test3")
                    );
Console.WriteLine(myElement.ToString());

Output :

<MyItem value1="test1" value2="test2" value3="test3" />



回答2:


Not directly related, but hope it helps someone. I wanted to removed the self self closing tag. That is, what I wanted is

<label id="txtInitialTemperatureErrorMessage" hidden="true" class="errorLocal"></label>

instead of

<label id="txtInitialTemperatureErrorMessage" hidden="true" class="errorLocal" />

What I did is simply the following.

Instead of

new XElement("label",     new XAttribute("id", "txt" + x.Key + "ErrorMessage"), new XAttribute("hidden", "true"), new XAttribute("class", "errorLocal")),

I did

new XElement("label", "", new XAttribute("id", "txt" + x.Key + "ErrorMessage"), new XAttribute("hidden", "true"), new XAttribute("class", "errorLocal")),

I had added a empty string for second parameter. The second parameter is for content.



来源:https://stackoverflow.com/questions/24485057/how-to-add-self-closing-tag-to-an-element-in-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!