【问题标题】:AddAfterSelf and line return with XDocumentAddAfterSelf 和行返回 XDocument
【发布时间】:2013-08-05 17:55:12
【问题描述】:

我有这段代码用于在 XDocument 对象中复制 xml 元素。

//get a copy of element
XElement element = new XElement(this._xmldoc.Descendants(name).LastOrDefault());
//add element
this._xmldoc.Descendants(name).LastOrDefault().AddAfterSelf(element);

[编辑]

这是我的“保存”方法

/// <summary>
/// Method used to save document
/// </summary>
/// <param name="filePath">file path</param>
public bool Save(string filePath)
{
    //value to return
    bool returnValue = true;
    //clean empty elements
    returnValue &= this.CleanEmptyElements();
    //normalize xml text
    returnValue &= this.NormalizeDocument();
    try
    {
        //save document
        this._xmldoc.Save(filePath);
    }
    catch (InvalidOperationException)
    {
        returnValue = false;
    }
    //if save operation has failed
    if (!returnValue)
        //delete file
        File.Delete(filePath);
    //end of method
    return returnValue;
}

[/编辑]

我的代码运行良好,但是在复制之后,我有一个小问题,我有这个 XML:

<?xml version="1.0" encoding="iso-8859-1"?>
<Invoice>
    <Party>
        <Country>FRANCE</Country>
    </Party><Party>
        <Country>SPAIN</Country>
    </Party>
</Invoice>

我想要这个 XML:

<?xml version="1.0" encoding="iso-8859-1"?>
<Invoice>
    <Party>
        <Country>FRANCE</Country>
    </Party>
    <Party>
        <Country>SPAIN</Country>
    </Party>
</Invoice>

所以我的问题是,如何在原始元素之后和副本之前返回一行?

谢谢

【问题讨论】:

  • 有什么理由不能在保存时重新格式化? (除非您指定 SaveSettings.DisableFormatting,否则我希望 XDocument.Save 自动执行此操作。)
  • 你是如何保存你的 _xmldoc 你能把这段代码也贴出来吗?
  • 我使用了保存方法,但是我的 xml 格式不是很好...
  • 你需要一个根元素,例如,Party 下面有你的 Party 元素
  • 空白(换行符)在 XML 中不相关...事实上,格式良好的 XML 文档只能有 1 个根元素。

标签: c# xml


【解决方案1】:

解析文档时,使用:

this._xmldoc = XDocument.Parse(yourXmlString);

代替:

this._xmldoc = XDocument.Parse(yourXmlString, LoadOptions.PreserveWhitespace);

【讨论】:

  • 我从不解析我的文档,我只创建一个 XDocument 并将其保存到一个文件中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多