簡體   English   中英

如何解析提取C#中XML節點描述中存在的值

[英]How To parse extract the values present in XML node description in C#

我能夠解析和提取xml標記內的內部文本。 我無法提取Job標簽中存在的值
我的Xml文件格式

    <?xml version="1.0" standalone="yes"?>
    <SmPpProperties>
     <SmProperties>
       <Job Name="Job001" CreatedDate="2012-10-15T10:43:56.0972966-06:00" ModifiedDate="2012-10-       15T10:46:07.6878231-06:00">
 //            **I am not able to extract the values present in above Job tag**
         <NuclearSystem>Barium</NuclearSystem>
                      </Job>
    </SmProperties>
 <SmPpProperties>

C#代碼

       // Load XML Document
             XmlDocument MyDoc = new XmlDocument(); 
       // Select Node     
       MyDoc.Load(@"C:\Users\SRangarajan\Desktop\12001_.xml");

            XmlNode MyNode = MyDoc.SelectSingleNode("SmPpProperties/SmProperties/Job");
            Console.WriteLine(String.Concat("NuclearSystem: ", MyNode.InnerText));
            Console.ReadKey();

XmlNode.InnerText返回節點及其子注釋的串聯 那會給你Barium 名稱,ModifiedDate和CreatedDate是屬性。

您的意圖尚不清楚,但是如果要獲取所有屬性的串聯值:

String.Join(",", MyNode.Attributes.Cast<XmlAttribute>().Select(a => a.Value))

或者您可以通過名稱或索引獲取特定屬性的值:

string name = MyNode.Attributes["Name"].Value;
string createdDate = MyNode.Attributes[1].Value;

注意:我總是建議您使用Linq到Xml來解析xml。 您可以輕松地從xml創建強類型對象:

var xdoc = XDocument.Load(@"C:\Users\SRangarajan\Desktop\12001_.xml");
XElement j = xdoc.Root.Element("SmProperties").Element("Job");
var job = new {
                Name = (string)j.Attribute("Name"),
                CreatedDate = (DateTime)j.Attribute("CreatedDate"),
                ModifiedDate = (DateTime)j.Attribute("ModifiedDate"),
                NuclearSystem = (string)j.Element("NuclearSystem")
            };

這將為您提供作業對象,該對象將具有名稱,創建日期和修改日期的強類型屬性。 並且date屬性將具有DateTime類型!

在此處輸入圖片說明

嘗試使用linq,像這樣:

string xml = "xml";
    XDocument xdoc = XDocument.Parse(xml);
    XElement nuclear = xdoc.Descendants(document.Root.Name.Namespace + "NuclearSystem").FirstOrDefault();

    string nuclearSystem = nuclear.Value();

為了獲得屬性,請使用Attributes屬性,然后訪問Value:

XmlNode MyNode = MyDoc.SelectSingleNode("SmPpProperties/SmProperties/Job");
Console.WriteLine(String.Concat("Name: ", MyNode.Attributes["Name"].Value));
Console.WriteLine(String.Concat("CreatedDate: ", MyNode.Attributes["CreatedDate"].Value));
Console.WriteLine(String.Concat("ModifiedDate: ", MyNode.Attributes["ModifiedDate"].Value));
Console.WriteLine(String.Concat("NuclearSystem: ", MyNode.InnerText));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM