如何在XDocument中插入空白字符

本文关键字:插入 空白 字符 XDocument | 更新日期: 2023-09-27 18:29:57

我正在创建一个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);

如何在XDocument中插入空白字符

如果您正在尝试执行类似的操作

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

那么它在xml语法中是非法的。如果你想实现这样的目标,那么你必须使用属性

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

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

名称中不能包含"字符(十六进制值0x20)。

正如错误所述,您可能不会在xml元素名称中放入空格。

更多信息可以在这里找到:

C#.Net 中XmlElement中的空白

我可以创建一个带有正斜杠的元素作为名称的一部分吗

我不确定为什么它不适合你-下面的代码片段适合我(需要以管理员身份运行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。