简体   繁体   English

使用StreamReader文本中的XElement创建新的XDocument

[英]Create new XDocument with XElement from StreamReader text

I'm trying to take an existing XML file and "embed" that into another node of another "Root" XML file. 我正在尝试获取一个现有的XML文件,并将其“嵌入”到另一个“根” XML文件的另一个节点中。 Suppose there's a path to an existing xml file... 假设有一个到现有xml文件的路径...

 StreamReader reader = new StreamReader(path);

    string lines = reader.ReadLine();
    while (!reader.EndOfStream)
    {
        lines = reader.ReadLine();
    }

    XDocument doc = new XDocument(
        new XComment("You can copy and paste or open the XML in Excel."),
        new XElement("Root",
            new XElement("logs",lines))
    );

I end up with things like this: 我最终得到这样的事情:

<Root><logs>&lt;log&gt;&lt;username&gt;otonomy&lt;/

Some decode encode help needed. 需要一些解码编码帮助。

Use XElement.Load() static method instead: 改用XElement.Load()静态方法:

XDocument doc = new XDocument(
        new XComment("You can copy and paste or open the XML in Excel."),
        new XElement("Root",
            new XElement("logs"
                XElement.Load(path)))
    );

It can take the path directly, so you don't have to deal with StreamReader at all. 它可以直接使用path ,因此您根本不必处理StreamReader

Try: 尝试:

string lines = File.ReadAllText( path );

XDocument doc = new XDocument(
    new XComment( "You can copy and paste or open the XML in Excel." ),
    new XElement( "Root",
        new XElement( "logs", XElement.Parse( lines ) ) ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM