是否有与XmlWriter.WriteRaw等效的XElement?

时间:2011-04-19 21:49:52

标签: .net xelement

我正在转换一些当前使用XmlWriter的代码来创建文档,而不是返回内容的XElement

到目前为止,我喜欢以模仿文档结构的方式构建代码,但是有些内容是使用XmlWriter.WriteRaw编写的,以避免重新缩小xml。我在System.Xml.Linq命名空间中找不到任何等价物。是否存在?

2 个答案:

答案 0 :(得分:3)

XElement.Parse()应该可以做到这一点。

例如:

XElement e = new XElement("root",
    new XElement("child",
        XElement.Parse("<big><blob><of><xml></xml></of></blob></big>"),
        new XElement("moreXml")));

答案 1 :(得分:2)

警告:仅适用于您的目的仅仅是为了呈现XML字符串,并且您确定内容已经是XML

由于XElement.Parse“重新xmlize”已经存在的XML,您可以将内容设置为'占位符'值(如建议的here)并将其替换为渲染输出:

var d = new XElement(root, XML_PLACEHOLDER);
var s = d.ToString().Replace(XML_PLACEHOLDER, child);

请注意,除非child已经拥有,否则不保证“相当格式化”。

在LinqPad中测试这个似乎表明'替换'比使用Parse更快:

void Main()
{
    // testing:
    // * https://stackoverflow.com/questions/1414561/how-to-add-an-existing-xml-string-into-a-xelement
    // * https://stackoverflow.com/questions/16586443/adding-xml-string-to-xelement
    // * https://stackoverflow.com/questions/587547/how-to-put-in-text-when-using-xelement
    // * https://stackoverflow.com/questions/5723146/is-there-an-xelement-equivalent-to-xmlwriter-writeraw

    var root = "root";
    var childContents = "<name>Fname</name><age>23</age><sex>None of your business</sex>";
    var child = "<child>" + childContents + "</child>";

    parse(root, child, true);
    replace(root, child, true);

// this fails, per https://stackoverflow.com/questions/16586443/adding-xml-string-to-xelement
try {
        parse(root, childContents, true);
    } catch(Exception ex) {
        ex.Dump();
    }
// this works, but again, you don't get the pretty formatting
    try {
        replace(root, childContents, true);
    } catch(Exception ex) {
        ex.Dump();
    }

    "Xml Parsing".Vs(new [] { "parse", "replace" }
        , n => parse(root, child, false)
        , n => replace(root, child, false)
    );
}

// Define other methods and classes here
void parse(string root, string child, bool print) {
    var d = new XElement(root, XElement.Parse(child));
    var s = d.ToString();
    if(print) s.Dump("Parse Result");
}

const string XML_PLACEHOLDER = "##c##";
void replace(string root, string child, bool print) {
    var d = new XElement(root, XML_PLACEHOLDER);
    var s = d.ToString().Replace(XML_PLACEHOLDER, child);
    if(print) s.Dump("Replace Result");
}

其中Vs is a wrapper function用于在秒表内运行每个代表10000次。