将任何用户输入添加为XML文档中的节点

时间:2013-09-27 07:17:24

标签: c# xml linq-to-xml xelement

我想将XML字符串添加为现有XML文档的新节点。

例如,假设用户的输入是:

<bk:book>
  <title>Pride And Prejudice</title>
  <authorlastname>Jane</authorlastname>
  <authorfirstname>Austen</authorfirstname>
  <price>24.95</price>
</bk:book>

我正在尝试按如下方式插入该用户输入:

xml_SourceDoc.Root.LastNode.AddAfterSelf(XElement.Parse(xmlString));

但是,该声明引发了这一异常:

bk is an undeclared prefix. Line 1, position 2.

如何更改我的方法,以便我可以成功插入用户输入的任何文本?

3 个答案:

答案 0 :(得分:2)

如果您确实不知道用户将输入什么内容,您只需通过 LINQ to XML {{CDATA将其处理为XCData Class 3}}

以下是在容器XML文档中作为节点插入时样本数据的样子:

<doc>
  <content><![CDATA[<bk:book>
   <title>Pride And Prejudice</title>
   <authorlastname>Jane</authorlastname>
   <authorfirstname>Austen</authorfirstname>
   <price>24.95</price>
 </bk:book>]]></content>
</doc>

这是一个创建上述示例文档的示例程序:

using System;
using System.Xml;
using System.Xml.Linq;

public class CDataExample
{
    public static void Main()
    {
        string documentXml = "<doc><content></content></doc>";
        XElement doc = XElement.Parse(documentXml, LoadOptions.None);

        string userInput =
 @"<bk:book>
   <title>Pride And Prejudice</title>
   <authorlastname>Jane</authorlastname>
   <authorfirstname>Austen</authorfirstname>
   <price>24.95</price>
 </bk:book>";

        XCData cdata = new XCData(userInput);
        doc.Element("content").Add(cdata);

        Console.WriteLine(doc.ToString());
    }
}

答案 1 :(得分:0)

首先检查xml是否可解析:

Check well-formed XML without a try/catch?

if(IsValidXML(xmlString))
{
    xml_SourceDoc.Root.LastNode.AddAfterSelf(XElement.Parse(xmlString));
}

答案 2 :(得分:0)

首先,创建要添加的XElement:

  

xmlString = new XElement(new XElement(“book”,new XAttribute(“bk),(new XElement(”title“,   titleValue),新的EXelement(“authorlastname”,authorlastNameValue ...   等等。

然后添加它:

xml_SourceDoc.Root.Add(xmlString);
你提到的

异常是因为你没有添加创建XElement的属性