我能够在xml标签中解析和提取内部文本。我无法提取作业标签中的值 我的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();
答案 0 :(得分:0)
XmlNode.InnerText返回节点及其子注释的连接值。这会给你Barium
。 Name,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 to 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")
};
为您提供作业对象,该对象将具有名称的强类型属性,创建日期和修改日期。日期属性将有DateTime
类型!
答案 1 :(得分:0)
尝试使用linq,如下所示:
string xml = "xml";
XDocument xdoc = XDocument.Parse(xml);
XElement nuclear = xdoc.Descendants(document.Root.Name.Namespace + "NuclearSystem").FirstOrDefault();
string nuclearSystem = nuclear.Value();
答案 2 :(得分:0)
要获取属性,请使用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));