简体   繁体   中英

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). 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?

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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