2013-10-18 68 views
1

我試圖用String替換現有的.xml擴展文件的內部文本。替換現有的xml文件的所有字符串?

爲什麼我這樣做是:我想從.xml文件讀取圖像。但圖像沒有從.xml文件的現有文件夾加載文件。我嘗試了很多次來解決這個問題。唯一可能的就是放置圖像文件目標的硬路徑。於是我開始嘗試這樣的:

  1. 讀取.xml文件的內部串 - 解決
  2. 獲得XML路徑的全父 - 解決內部XML和出口
  3. 讀取文本字符串 - 解決
  4. 發現「<img src='」存在從弦面積 - 解決
  5. 把父路徑存在後區 - 解決
  6. 字符串保存現有的.xml替換所有的字符串 - 未解?

工作目的是「從XML文件顯示圖像」。所以請有人回答未解決的文章。 而且不要向我推薦像Base64ToImage這樣的方法。我只想這樣走。希望我會在這裏得到我的答案。

現有的XML: <helpRoot> <body Type="Section1"> <![CDATA[ <img src='Help1.png'/>
<h3 style="color:#2B94EA;font-family:open sans;">Section1</h3></hr>
<p style="color:#484848;font-family:open sans;">Text is shown</p> <h3 style="color:#3399FF;font-family:open sans;"> Image is not showing</h3></hr>
]]></body> <body Type="Section2"> <![CDATA[ <img src='Help2.png'/>
<h3 style="color:#2B94EA;font-family:open sans;">Section2</h3></hr>
<p style="color:#484848;font-family:open sans;">Text is shown</p> <h3 style="color:#3399FF;font-family:open sans;"> Image is not showing</h3></hr>
]]></body> ... </helpRoot>

新的XML字符串: <helpRoot> <body Type="Section1"> <![CDATA[ <img src='D:/Project/Image/Help1.png'/>
<h3 style="color:#2B94EA;font-family:open sans;">Section1</h3></hr>
<p style="color:#484848;font-family:open sans;">Text has showing</p> <h3 style="color:#3399FF;font-family:open sans;"> Image is showing</h3></hr>
]]></body> <body Type="Section2"> <![CDATA[ <img src='D:/Project/Image/Help2.png'/>
<h3 style="color:#2B94EA;font-family:open sans;">Section2</h3></hr>
<p style="color:#484848;font-family:open sans;">Text has shown</p> <h3 style="color:#3399FF;font-family:open sans;"> Image is not showing</h3></hr>
]]></body> ... </helpRoot>

+2

你的問題很混亂。如果你的意思是你想操作XML文件,那麼如果你要顯示一個樣本輸入和所需的輸出,這將非常有用。我強烈建議你*不要在這裏使用字符串替換。使用XML API將它作爲* XML操作。 –

+0

您是否只有保存新形成的xml文件時出現問題,因爲您已經將字符串成功添加到xml的第5點? – azmuhak

+1

是的,我只是想保存我的「準備」字符串而不是.xml文件中的文本並顯示結果。 – mangasm

回答

0

我會使用XDocumentHTMLAgilityPack

var xml = 
@"<base> 
    <child><![CDATA[<img src=""/path"" />]]></child> 
</base>"; 

var xDocument = XDocument.Parse(xml); 

var xChild = xDocument.Descendants("child").First(); 

var cData = xChild.Nodes().OfType<XCData>().First(); 

var htmlDocument = new HtmlDocument(); 

htmlDocument.LoadHtml(cData.Value); 

var imgNode = htmlDocument.DocumentNode.SelectSingleNode("img"); 

imgNode.Attributes["src"].Value = "/new/path"; 

using (var writer = new StringWriter()) 
{ 
    htmlDocument.Save(writer); 
    cData.Value = writer.ToString(); 
} 

xDocument現在包含:

<base> 
    <child><![CDATA[<img src="/new/path">]]></child> 
</base> 
+0

是的,對於處理XML我也會用'XDocument'去。但是從你的問題我不確定你的問題到底是什麼。 – DeadDog

+0

感謝@dav_i的貢獻。但是我的XML文件包含了很多CDATA。所有CDATA內部都有很多標籤。所以我只想用我處理過的XML字符串替換現有的XML內容。任何其他建議:) – mangasm

+0

@mangasm使用上面沒有所有的HTMLAgility的東西,檢查我的[以前的修訂](http://stackoverflow.com/revisions/19444863/1) –

相關問題