2010-08-23 64 views
0

埃爾Padrino呈溶液:直接訪問和編輯到XML節點,使用屬性

How to change XML Attribute

其中XML元素可以直接加載(沒有爲每個..),編輯和保存!

我的XML是:

<?xml version="1.0" encoding="ISO-8859-8"?> 
<g> 
    <page no="1" href="page1.xml" title="נושא 1"> 
    <row> 
     <pic pos="1" src="D:\RuthSiteFiles\webSiteGalleryClone\ruthCompPics\C_WebBigPictures\100CANON\IMG_0418.jpg" width="150" height="120">1</pic> 
    </row> 
    </page> 
</g> 

,我需要通過兩個屬性來選擇節點

我」(1 「不」,在頁面的標籤,並在PIC標記 「POS」)。 ve發現: How to access a xml node with attributes and namespace using selectsinglenode()

直接訪問是可能的,但除了我不明白的解決方案,我認爲它使用xpath對象,它不能被修改和保存更改。

什麼是

  1. 直接訪問XML節點(我負責該節點將是唯一的)
  2. 編輯節點
  3. 更改保存到XML
的最佳方式

謝謝 Asaf

回答

0

使用新的,精心設計的XDocument/XElement,而不是舊XmlDocument API。

在你的榜樣,

XDocument doc = XDocument.Load(filename); 

var pages = doc.Root.Elements("page").Where(page => (int?) page.Attribute("no") == 1); 
var rows = pages.SelectMany(page => page.Elements("row")); 
var pics = rows.SelectMany(row => row.Elements("pic").Where(pic => (int?) pic.Attribute("pos") == 1)); 

foreach (var pic in pics) 
{ 
    // outputs <pic pos="1" src="D:\RuthSiteFiles\webSiteGalleryClone\ruthCompPics\C_WebBigPictures\100CANON\IMG_0418.jpg" width="150" height="120">1</pic> 
    Console.WriteLine(pic); 

    // outputs 1 
    Console.WriteLine(pic.Value); 

    // Changes the value 
    pic.Value = 2; 
} 

doc.Save(filename); 
+0

XDocument幫助我在一個對象上執行我需要的xml文件上的每個操作。 但我無法做類似a = pic [0]; 任何方式非常感謝 – Asaf 2010-08-23 15:57:38

+0

@Asaf:如果你在'pics'聲明的末尾寫了'.ToArray()',那麼你可以去'pics [0]'。但是,如果你不需要這樣的數組,那麼'pic.First()'是最有效的解決方案。 – Timwi 2010-08-23 18:32:58

1

您可以使用與第一個答案相同的模式您鏈接到了,但您需要在XPath中的屬性中包含條件。您的基本XPath將是g/page/row/pic。由於您希望pageno屬性爲1,因此您在page上添加[@no='1']作爲謂詞。因此,完整的XPath查詢類似於g/page[@no='1']/row/pic[@pos='1']。 SelectSingleNode將返回一個可變的XmlNode對象,因此您可以修改該對象並保存原始文檔以保存更改。

把的XPath連同El Padrino's answer

//Here is the variable with which you assign a new value to the attribute 
string newValue = string.Empty; 
XmlDocument xmlDoc = new XmlDocument(); 

xmlDoc.Load(xmlFile); 

XmlNode node = xmlDoc.SelectSingleNode("g/page[@no='1']/row/pic[@pos='1']"); 
node.Attributes["src"].Value = newValue; 

xmlDoc.Save(xmlFile); 

//xmlFile is the path of your file to be modified 
+0

+1感謝,它爲我工作。 – Asaf 2010-08-23 15:53:58