如何连接字符串-我知道这并不难! [英] How to concatenate strings -I know it's not that hard!
问题描述
我必须处理一个wannabe XML字符串.
它没有根元素(由于未知原因),但是我对此无能为力.
因此,我决定在整个XML上粘贴一个虚拟的根节点,然后将其馈入XMLDocument
.
有问题的XML如下:
I have to process a wannabe XML string.
It hasn''t got a root element (for reasons unknown), but I can''t do much about it.
So I decided to stick a dummy root node around the entire XML and then feed it into the XMLDocument
.
The XML in question looks like:
<mynode>
blah
<morenodes>
blah
blah
</morenodes>
</mynode>
blah
<morenodes>
blah
blah
</morenodes>
...
所以为了作弊,我决定去做
So to cheat, I decided to do
<root>
<mynode>
blah
<morenodes>
blah
blah
</morenodes>
</mynode>
<mynode>
blah
<morenodes>
blah
blah
</morenodes>
</mynode>
...
</root>
认为这很简单,我做到了
Thinking this is fairly straight forward, I did
string newString = "<root>" + oldString + "</root>";
XMLDocument xmlDolcument = new XMLDocument();
xmlDocument.Load(newString);
oldString
是找到原始XML的位置.
由于某些原因,< Root>标记添加成功,但</Root>拒绝添加任何我尝试的内容.
字符串连接有什么难处,我该怎么办呢,这太可怕了吗?
请帮忙!
格式错误,结尾标记消失了.
where oldString
is where the original XML is found.
For some reason, the <Root> tag gets added OK, but the </Root> refuses to be added whatever I try.
What''s so hard about string concatenation, and what am I doing that''s so horribly wrong?
Please help!
Formatting went wrong and the ending tag disappeared...
推荐答案
您的代码(即使我查看了问题的原始来源)也没有添加结束标签!
试试:
Your code (even if I view the raw source of your question) doesn''t add the ending tag!
Try:
string newString = "<root>" + oldString + "</root>";
XMLDocument xmlDolcument = new XMLDocument();
xmlDocument.Load(newString);
请注意,字符串是不可变的,因此,如果您有多个"+"操作,则每次都会一次又一次地复制整个字符串.
首选System.Text.StringBuilder.Append
.如果要连接静态固定数量的字符串(而不是循环),请使用string.Format
.
—SA
Be careful, remember, strings are immutable, so if you have several "+" operations, whole string is copied again and again every time.
PreferSystem.Text.StringBuilder.Append
. If you want to concatenate statically fixed number of strings (not a loop), preferstring.Format
.
—SA
这篇关于如何连接字符串-我知道这并不难!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!