2014-01-08 49 views
1

我試圖訪問XML的子節點,但我的第一個XML節點具有間距和引號作爲屬性。用間距和引號修改xml節點作爲attricutes

var xml = @"<Envelope xsd "http"> 
      <Catalog> 
       <Price> 
        <Value Default ="yes">P1</Value> 
       </Price> 
      </Catalog> 
     </Envelope>"; 

我試圖將Default的屬性值從「yes」更改爲「1」,但節點始終返回null。

XmlDocument doc = new XmlDocument(); 
doc.LoadXml(xml); 
var node = doc.SelectSingleNode("/*/Catalog/Price/Value"); 

任何想法?

回答

0

我不認爲這是有效的XML的根,你也許意味着以下

using System; 
using System.Globalization; 
using System.Xml; 

namespace ConsoleApplication9 
{ 
    class Program 
    { 
     private static void Main(string[] args) 
     { 
      //Valid XML 
      string xml = @"<Envelope xsd='http'> 
          <Catalog> 
          <Price> 
           <Value Default='yes'>P1</Value> 
          </Price> 
          </Catalog> 
         </Envelope>"; 
      var doc = new XmlDocument(); 
      doc.LoadXml(xml); 

      //Select the Value Node 
      XmlNode node = doc.SelectSingleNode("/*/Catalog/Price/Value"); 

      //Set the Default attribute to 1 
      node.Attributes["Default"].Value = 1.ToString(CultureInfo.InvariantCulture); 

      //Check the output 
      Console.WriteLine(doc.InnerXml.ToString(CultureInfo.InvariantCulture)); 

      //Press enter to exit 
      Console.ReadLine(); 
     } 
    } 
} 

隨便說。

+0

我從xsd生成了xml。它實際上看起來像這樣 Hann

+0

在這種情況下,請仔細檢查http://msdn.microsoft.com/en-us/library/x6c1kb0s(v=vs .110).aspx以確保您擁有正確的所有選項。 –

+1

謝謝。標記這是答案,因爲它給了正確的方向。 – Hann

0

這可能顯得有些硬編碼的,但它應該工作:

XmlDocument doc = new XmlDocument(); 
    doc.LoadXml(xml); 
    Namespace ns= "http"; //set the namespace of the root node here 

    //the following is where you change the value to 1 

doc.Document.Descendants(ns+"Envelope").FirstorDefault().Descendants(ns+"Catalog").Descendants(ns+"Price").FirstorDefault().Elements("Value").Attribute("Default").SetValue("1"); 

此外,XML看起來有點我錯了,因爲有人提到,根節點需要加以糾正。