用字符串连接构建 XML 有什么不好? [英] What's so bad about building XML with string concatenation?

查看:30
本文介绍了用字符串连接构建 XML 有什么不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在线程中 你最喜欢的程序员无知"宠物是什么peeve?,下面的答案出现了,得到了大量的赞成:

In the thread What’s your favorite "programmer ignorance" pet peeve?, the following answer appears, with a large amount of upvotes:

使用字符串连接构建 XML 的程序员.

我的问题是,为什么通过字符串连接(例如 C# 中的 StringBuilder)构建 XML 不好?

My question is, why is building XML via string concatenation (such as a StringBuilder in C#) bad?

过去我已经这样做了几次,因为当涉及到我正在使用的数据结构/对象时,它有时是我从 A 点到达 B 点的最快方式.到目前为止,我已经提出了一些为什么这不是最好的方法的原因,但是有什么我忽略的地方吗?为什么要避免这种情况?

I've done this several times in the past, as it's sometimes the quickest way for me to get from point A to point B when to comes to the data structures/objects I'm working with. So far, I have come up with a few reasons why this isn't the greatest approach, but is there something I'm overlooking? Why should this be avoided?

  1. 可能我能想到的最大原因是您需要手动转义字符串,而大多数新程序员(甚至一些有经验的程序员)都会忘记这一点.当他们测试它时,这对他们很有用,但是当有人抛出 & 时,他们的应用程序将随机"失败.他们在某处输入的符号.好的,我会买这个,但它真的很容易防止这个问题(SecurityElement.Escape 来命名一个).
  2. 执行此操作时,我通常会省略 XML 声明(即 <?xml version="1.0"?>).这有害吗?
  3. 绩效处罚?如果您坚持使用正确的字符串连接(即 StringBuilder),这有什么值得关注的吗?据推测,像 XmlWriter 这样的类也需要做一些字符串操作......
  4. 有更优雅的生成 XML 的方法,例如使用 XmlSerializer 自动序列化/反序列化您的类.好的,我同意.C#为此提供了大量有用的类,但有时我不想为某些非常快速的事情创建一个类,例如写出日志文件或其他东西.这只是我懒惰吗?如果我正在做一些真实"的事情,这是我处理 XML 的首选方法.
  1. Probably the biggest reason I can think of is you need to escape your strings manually, and most new programmers (and even some experienced programmers) will forget this. It will work great for them when they test it, but then "randomly" their apps will fail when someone throws an & symbol in their input somewhere. Ok, I'll buy this, but it's really easy to prevent the problem (SecurityElement.Escape to name one).
  2. When I do this, I usually omit the XML declaration (i.e. <?xml version="1.0"?>). Is this harmful?
  3. Performance penalties? If you stick with proper string concatenation (i.e. StringBuilder), is this anything to be concerned about? Presumably, a class like XmlWriter will also need to do a bit of string manipulation...
  4. There are more elegant ways of generating XML, such as using XmlSerializer to automatically serialize/deserialize your classes. Ok sure, I agree. C# has a ton of useful classes for this, but sometimes I don't want to make a class for something really quick, like writing out a log file or something. Is this just me being lazy? If I am doing something "real" this is my preferred approach for dealing w/ XML.

推荐答案

您可能会以无效的 XML 结束,但直到您再次解析它时您才会发现 - 然后为时已晚.我是通过艰难的方式了解到这一点的.

You can end up with invalid XML, but you will not find out until you parse it again - and then it is too late. I learned this the hard way.

这篇关于用字符串连接构建 XML 有什么不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆