如何在XDocument中插入空格字符

时间:2013-09-02 09:56:21

标签: c# xml linq-to-xml

我正在创建一个Xml XDocument。当我尝试插入一个包含字母,空格,特殊字符和数字的字符串。它在运行时出错。

The ' ' character, hexadecimal value 0x20, cannot be included in a name.

我如何插入这种类型的字符串。有没有其他方法可以插入这种类型的字符串。

我正在使用的代码:

XDocument xDoc = new XDocument(
                   new XDeclaration("1.0", "UTF-8", "yes"),
                   new XElement("Mail"));
var template = @"To MOM 
            13, AD1
            tr y
            fghdh, Madhya Pradesh, India 

            Dear Ram,
                  We would like to appoint you for new job";
XElement varXElement = new XElement("studentName", template);
xDoc.Element("Mail").Add(varXElement);
xDoc.Save(filePath);

3 个答案:

答案 0 :(得分:1)

如果你想做这样的事情

<some text some>ABAC</some text some>

然后它在xml语法中是非法的。 如果你想实现这样的东西,你必须使用属性

<node name ="some text some">ABAC</node >

但很难从你的问题中猜出你的问题是什么。

答案 1 :(得分:1)

  

''字符,十六进制值0x20,不能包含在名称中。

由于错误声明您可能没有在xml元素名称中添加空格。

可在此处找到更多信息:

White space in XmlElement in C# .Net

Can I create an element with forward slash as part of the name

答案 2 :(得分:1)

我不确定为什么它不适合你 - 以下代码片段适合我(需要以管理员身份运行VS以保存到C的根目录):

using System;
using System.Xml.Linq;

namespace ConsoleApplication4
{
    class Program
    {

        static void Main(string[] args)
        {

            XDocument xDoc = new XDocument(
                   new XDeclaration("1.0", "UTF-8", "yes"),
                   new XElement("Mail"));
            var template = @"To MOM 
            13, AD1
            tr y
            fghdh, Madhya Pradesh, India 

            Dear Ram,
                  We would like to appoint you for new job";
            XElement varXElement = new XElement("studentName", template);
            xDoc.Element("Mail").Add(varXElement);
            xDoc.Save("C:\\doc.xml");

            Console.ReadLine();
        }
    }
}

这会生成以下XML:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Mail>
  <studentName>To MOM 
            13, AD1
            tr y
            fghdh, Madhya Pradesh, India 

            Dear Ram,
                  We would like to appoint you for new job</studentName>
</Mail>

这是在Win7 64位计算机上使用VS 2012 Premium。

相关问题