2015-06-27 101 views
0

讓我們假設我有這樣的XML節點方案進行更換:毫升就像thisChange XML節點名稱/使用XML節點(C#)

<mat id="4230348"> 
     <home id="2339086"/><away id="2339218"/> 
      <os/> 
</mat> 

如何更改節點<os/><os></os>因爲它會導致一個解析問題? 當XML是這樣的(包含標籤之間的信息,解析是確定的:

<mat id="4230348"> 
     <home id="2339086"/><away id="2339218"/> 
      <os> <a> <b> </b </a> </os> 
</mat> 

它讀取的東西... ,如果有其他地方的一個節點,其是這樣的:

<mat id="4230348"> 
      <home id="2339086"/><away id="2339218"/> 
       <os/> 
    </mat> 

它無法讀取XML文件的其餘部分

+0

我不清楚「其中」你想這種變化。 XML源文件是一個文本文件,您可以相應地編輯它。您沒有指定「解析問題」是什麼,但是您可能希望能夠將XML源輸入到DOM對象並在其中進行操作? – hardmath

+0

您是否需要驗證輸入文件並刪除/修復損壞的節點以繼續解析? – Artem

+0

現在的xml是有效的,但我無法用HtmlAgilityPack中的XmlNode方法或HtmlNode解析它。我只想XML節點變成 ...只是改變字符串如果XML作爲atxt文件 – ABCDD

回答

0

嘗試XML的LINQ。LINQ的,你可以投一個元素爲字符串,所以如果該項目是空你不會得到一個異常

using System; 
 
using System.Collections.Generic; 
 
using System.Linq; 
 
using System.Text; 
 
using System.Xml; 
 
using System.Xml.Linq; 
 

 
namespace ConsoleApplication1 { 
 
    class Program 
 
    { 
 
     static void Main(string[] args) 
 
     { 
 
      string input = 
 
      "<Root>" + 
 
      "<mat id=\"4230348\">" + 
 
       "<home id=\"2339086\"/><away id=\"2339218\"/>" + 
 
       "<os/>" + 
 
      "</mat>" + 
 
      "<mat id=\"4230349\">" + 
 
       "<home id=\"2339086\"/><away id=\"2339218\"/>" + 
 
       "<os/>" + 
 
      "</mat>" + 
 
      "<mat id=\"4230350\">" + 
 
       "<home id=\"2339086\"/><away id=\"2339218\"/>" + 
 
       "<os>info</os>. " + 
 
      "</mat>" + 
 
      "<mat id=\"4230351\">" + 
 
       "<home id=\"2339086\"/><away id=\"2339218\"/>" + 
 
       "<os/>" + 
 
      "</mat>" +    
 
      "</Root>"; 
 

 
      XDocument doc = XDocument.Parse(input); 
 
      var results = doc.Descendants("mat") 
 
       .Select(x => new { 
 
        matId = x.Attribute("id").Value, 
 
        homeId = x.Element("home").Attribute("id").Value, 
 
        awayId = x.Element("away").Attribute("id").Value, 
 
        os = (string)x.Element("os") 
 
       }) 
 
      .ToList(); 
 

 
     } 
 
    } 
 
} 
 
​

+0

xml中有多個mat節點。有的有,有的有信息。當解析出現時,它無法讀取其餘的xml。 – ABCDD

+0

更新的代碼。使用Linq,你可以將一個元素轉換爲一個字符串,所以如果該項爲null,你將不會得到異常。用Root包裝代碼,這樣你只有一個根節點。 – jdweng