X元素& UTF-8问题
我有一个 .NET Web 服务(.asmx,而不是 .svc),它通过 HTTP POST 接受字符串。它接受的字符串是 xml 信息集,然后我通过 XElement.Parse 进行解析。解析为 XElement 实例后,我将一个节点添加到该实例内的元素之一。
我遇到的问题是,如果表示 xml 信息集的字符串由于某种原因出现,那么我向元素 XElement 添加节点会引发异常,例如“' ',十六进制值 0x06,是无效字符。行1、位置40”。我收到大量抛出的 0x(*) 错误。如果我不尝试向 XElement 添加节点,一切都会很好。以下是我添加元素的方式:
var prospect = doc.Element("prospect");
var provider = prospect.Element("provider");
provider.Add(new XElement("id",
new XAttribute("reservation-code",
reservationCode)
));
是否应该在某处进行某种字符串转换?
I have a .NET Web Service(.asmx, not .svc) that accepts a string via HTTP POST. The strings it accepts are xml infosets I then parse via XElement.Parse. Once parsed into an XElement instance, I add a node to one of the elements within the instance.
The problem I'm having is that if a string representing an xml infoset comes through with then for some reason, me adding a node to the element XElement throws an exception such as "' ', hexadecimal value 0x06, is an invalid character. Line 1, position 40.". I get a wide array of 0x(*) errors thrown. If I don't attempt to add nodes to the XElement, everythings fine. Here's how I'm adding the element:
var prospect = doc.Element("prospect");
var provider = prospect.Element("provider");
provider.Add(new XElement("id",
new XAttribute("reservation-code",
reservationCode)
));
Is there some sort of string conversion I ought to be doing somewhere?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
XML 不允许某些 Unicode 字符。请参阅XML 1.0 规范。不幸的是,在 XML 中也没有标准方法来转义这些字符。例如,由于格式正确性约束:合法字符,您无法使用
在有效的 XML 中对其进行转义(请参阅 字符引用)。
XElement.ToString()
打开了对这些字符的检查。然而,.NET 确实提供了一种关闭字符检查的方法。默认情况下,它在System.Xml.XmlWriter
实例中处于关闭状态。因此,以下代码将起作用:但请注意,如果您使用
System.Xml.XmlWriterSettings
创建System.Xml.XmlWriter
实例,则默认值为true 用于字符检查。因此,如果您使用 System.Xml.XmlWriterSettings 并希望关闭字符检查,请使用:
XML does not allow some Unicode characters. See the XML 1.0 Specification. Unfortunately, there is no standard way to escape those characters in XML, too. For example, you cannot escape it in valid XML using
because of the Well-formedness constraint: Legal Character (see character references).
The
XElement.ToString()
has the check for those characters turned on. However, .NET does provide a way to turn character checking off. It is off by default in theSystem.Xml.XmlWriter
instances. Therefore the following code will work:Notice however that if you create an
System.Xml.XmlWriter
instance usingSystem.Xml.XmlWriterSettings
, the default istrue
for character checking. Therefore if you useSystem.Xml.XmlWriterSettings
and want to turn off character checking, use:非常感谢,这解决了我使用 linq to xsd 时的问题。
这是我的代码:
//不使用container.Save(new StreamWriter(toStream, new UTF8Encoding(false)));
而是使用代码:
thanks a lot, which solved my problem when I using linq to xsd.
here is my code:
//not using
container.Save(new StreamWriter(toStream, new UTF8Encoding(false)));
instead using codes: