繁体   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