简体   繁体   English

将XML文档的一部分创建为字符串

[英]Creating a part of XML document as a string

I get a set of 'Attributes' with default values and I want to create a string which is a part xml document as below(not a complete xml document). 我得到一组带有默认值的“属性”,我想创建一个字符串,该字符串是下面的一部分xml文档(不是完整的xml文档)。 I want to have a 'tab' in between every attribute. 我希望每个属性之间都有一个“标签”。 I've found string concatenation is the workable option in this case. 我发现在这种情况下,字符串连接是可行的选项。 In .Net is there any better way of doing this? 在.Net中,有什么更好的方法吗?

<XmlNodes>
<ChildNode Attribute1 ="100"    Attribute2="200"    Attribute3 ="0"/>
<ChildNode Attribute1="100"     Attribute2="200"    Attribute3 ="0"/>
...
</XmlNodes>

Here's a fun little hack that at least only resorts to string manipulation late in the piece: 这是一个有趣的小技巧,至少在文章的后期至少要诉诸于字符串操作:

var nodes = new XElement("XmlNodes");
foreach (var i in Enumerable.Range(1,10))
{
    nodes.Add(new XElement("ChildNode", 
        new XAttribute("Attribute1", 100), 
        new XAttribute("Attribute2", 200), 
        new XAttribute("Attribute3", 0)));
}

var result = nodes.ToString().Replace("\" A", "\"\tA"); // **" A** becomes **"\tA**

But I maintain that if this is about providing 'templates' for people to edit then you're best off getting them to edit it in a non-XML format (like CSV) and then convert to XML when you parse it. 但是我坚持认为,如果这是要提供供人们编辑的“模板”,那么最好让他们以非XML格式(例如CSV)对其进行编辑,然后在解析时转换为XML。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM