XComment在结束标记之前添加
问题描述:
Visual Studio 2008.我正在使用System.Xml.Linq。XComment在结束标记之前添加
我在写一个XDocument XML文件,我想在XML元素之前或之后添加注释行。
由于某种原因,XML序列化程序将注释插入XML元素的中间。
// Create an XComment
//
string roleComment = string.Format("{0} Role ID={1}", myRole.roleType, myRole.roleId);
XComment xRoleComment = new XComment(roleComment);
// Create an XElement
//
XElement xRoleId = new XElement("Role_id", myRole.GUID);
// Add the XComment to the XElement
xRoleId.Add(xRoleComment);
我的输出最终意外地结束标记之前的评论:
<Role_id>2510<!--ROLE_TYPE_MASTER Role ID=130--></Role_id>
如何添加注释,以便它结束元素标记之外?之前或之后是好的。
答
您可以在注释节点添加到Role_id
element.First的父获取父然后添加XComment
。或者创建Role_id
父元素:
XElement parent = new XElement("parent",
new XElement("Role_id", myRole.GUID),
new XComment(roleComment));
或者使用XElement.AddAfterSelf
方法:
xRoleId.AddAfterSelf(xRoleComment);
添加到父母,谢谢。尽管如此,我还是觉得奇怪的是评论最终在标签内部结束了。 –
@JohnJesus因为你直接将它添加到元素中。这就是'Add'方法的作用。:) –
啊对了。是的,如果我添加了一个子元素,它也会在标签之间。得到它了。 –