2013-08-05 51 views
0

我有這個代碼來dupplicate XDocument對象中的xml元素。AddAfterSelf和線返回與XDocument

//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; 
} 

[/編輯]

我的代碼工作不錯,但dupplication後,我有一個小問題我有這個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> 

所以我的問題是,如何讓我的原始元素後,我的副本前行的回報?

感謝

+2

任何原因,你不能只是重新格式化救? (我希望'XDocument.Save'自動執行此操作,除非您指定'SaveSettings.DisableFormatting'。) –

+0

您如何保存您的_xmldoc您是否也可以發佈此代碼? – TheKingDave

+0

我使用保存方法,但我的XML不是'很好'格式... –

回答

0

當你解析文檔,使用:的

this._xmldoc = XDocument.Parse(yourXmlString); 

代替:

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

我永遠不會解析我的文檔,我只創建一個XDocument並將其保存到文件中 –