是否有一个等效于XmlWriter.WriteRaw的XElement?

| 我正在转换一些当前使用ѭ0来创建文档的代码,而不是返回ѭ1的内容。 到目前为止,我很喜欢以模仿文档结构的方式来构造代码,但是有些内容是使用
XmlWriter.WriteRaw
编写的,以避免重新将xml xml化。我在
System.Xml.Linq
命名空间中找不到任何等效项。是否存在?     
已邀请:
XElement.Parse()
就可以了。 例如:
XElement e = new XElement(\"root\",
    new XElement(\"child\",
        XElement.Parse(\"<big><blob><of><xml></xml></of></blob></big>\"),
        new XElement(\"moreXml\")));
    
注意:仅当您的目的只是为了呈现XML字符串并且您确定内容已经是XML时才适用 由于
XElement.Parse
“重新xmlizes”已经存在的XML,因此您可以将内容设置为\'placeholder \'值(如此处建议),并将其替换为呈现的输出:
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
是包装函数,用于在秒表内运行每个委托10000次。     

要回复问题请先登录注册