2013-02-06 28 views
0

我想使用XmlDocument()來讀取節點的XML文件節點輸出每個元素。對具有xmlns屬性的節點使用XmlDocument()?

經過多次試錯後,我確定在我的節點上具有xmlns屬性不會導致從SelectNodes()調用返回節點。不知道爲什麼。

由於我無法更改輸出格式並且無法訪問實際的命名空間,因此我有什麼方法可以解決此問題?

另外,我有一些有子節點的元素。如何在循環瀏覽XML文件時訪問這些文件? I.E.,我需要解密CipherValue元素,但不知道如何訪問此節點?

示例如下:

doc.Load(@"test.xml"); 
XmlNodeList logEntryNodeList = doc.SelectNodes("/Logs/LogEntry"); 
Console.WriteLine("Nodes = {0}", logEntryNodeList.Count); 
foreach (XmlNode xn in logEntryNodeList) 
{ 
    string dateTime = xn["DateTime"].InnerText; 
    string sequence = xn["Sequence"].InnerText; 
    string appId = xn["AppID"].InnerText; 
    Console.WriteLine("{0} {1} {2}", dateTime, sequence, appId); 
} 

示例XML看起來是這樣的:

<Logs> 
<LogEntry Version="1.5" PackageVersion="10.10.0.10" xmlns="http://private.com"> 
    <DateTime>2013-02-04T14:05:42.912349-06:00</DateTime> 
    <Sequence>5058</Sequence> 
    <AppID>TEST123</AppID> 
    <StatusDesc> 
    <EncryptedData> 
     <CipherData xmlns="http://www.w3.org/2001/04/xmlenc#"> 
     <CipherValue>---ENCRYPTED DATA BASE64---</CipherValue> 
     </CipherData> 
    </EncryptedData> 
    </StatusDesc> 
    <Severity>Detail</Severity> 
</LogEntry> 
<LogEntry Version="1.5" PackageVersion="10.10.0.10" xmlns="http://private.com"> 
    <DateTime>2013-02-04T14:05:42.912350-06:00</DateTime> 
    <Sequence>5059</Sequence> 
    <AppID>TEST123</AppID> 
    <StatusDesc> 
    <EncryptedData> 
     <CipherData xmlns="http://www.w3.org/2001/04/xmlenc#"> 
     <CipherValue>---ENCRYPTED DATA BASE64---</CipherValue> 
     </CipherData> 
    </EncryptedData> 
    </StatusDesc> 
    <Severity>Detail</Severity> 
</LogEntry> 
</Logs> 

回答

0

您可以使用LINQ到XML(作爲喬恩說)。這裏是解析你的xml文件的命名空間的代碼。結果是一個強類型的匿名對象序列(即Date屬性具有DateTime類型,Sequence是整數,AppID是一個字符串):

XDocument xdoc = XDocument.Load("test.xml"); 
XNamespace ns = "http://private.com"; 
var entries = xdoc.Descendants("Logs") 
        .Elements(ns + "LogEntry") 
        .Select(e => new { 
         Date = (DateTime)e.Element(ns + "DateTime"), 
         Sequence = (int)e.Element(ns + "Sequence"), 
         AppID = (string)e.Element(ns + "AppID") 
        }).ToList(); 

Console.WriteLine("Entries count = {0}", entries.Count);  

foreach (var entry in entries) 
{ 
    Console.WriteLine("{0}\t{1} {2}", 
         entry.Date, entry.Sequence, entry.AppID); 
} 
+0

我會試試看 - 如何處理子節點? – user500741

+0

我改成.NET 4.0完整,但得到的。選擇 – user500741

+0

錯誤此錯誤「System.Collections.Generic.IEnumerable 」不包含「選擇」的定義和沒有擴展方法'Select'接受類型'System.Collections.Generic.IEnumerable '的第一個參數可以找到(你是否缺少using指令或程序集引用?) – user500741

1

經過大量試驗和錯誤,我確定存在具有了xmlns我的節點上的屬性不會導致節點從SelectNodes()調用返回。不知道爲什麼。

xmlns屬性有效地改變了元素,內默認的命名空間包括元素本身。所以你的LogEntry元素的命名空間是"http://private.com"。您需要在XPath查詢中正確包含此內容,可能是通過XmlNamespaceManager

(如果你可以使用LINQ到XML相反,它使容易與命名空間的工作。)

相關問題