简体   繁体   English

使用c#将xml元素提取为字符串

[英]Extracting xml element into a string using c#

I have an xml file, as per the sample below:我有一个 xml 文件,如下面的示例所示:

  <Header>
<CollectionDetails>
  <Collection></Collection>
  <Year>1415</Year>
  <FilePreparationDate></FilePreparationDate>
</CollectionDetails>
<Source>
  <ProtectiveMarking>PROTECT-PRIVATE</ProtectiveMarking>
  <UKPRN></UKPRN>
  <TransmissionType>A</TransmissionType>
  <SoftwareSupplier></SoftwareSupplier>
  <SoftwarePackage></SoftwarePackage>
  <Release>12.0.2.3</Release>
  <SerialNo>01</SerialNo>
  <DateTime>2015-10-22T17:01:51.800</DateTime>
</Source>

Within Header, I want to take out the "Year" value which is what i'm stuck on how to do.在 Header 中,我想取出“Year”值,这是我一直坚持的方法。 My current C# uses the below to read the file initially, but I can't get what I need from it so I can turn it into a string:我当前的 C# 最初使用以下内容读取文件,但我无法从中获取所需内容,因此可以将其转换为字符串:

            XElement document = XElement.Load(str_FileLocation);
            var year = document.Element("Header");
            var year1 = year.Elements("CollectionDetails");
            var year2 = year1.Nodes("Year");

This is really straightforward with your XDocument :这对于您的XDocument来说非常简单:

XNamespace ns = "<default namespace here>"
var value = (string) doc.Descendants(ns + "Year").Single()

Where ns should be set to the default namespace as specified in the xmlns="..." attribute in an ancestor element (likely the document root).其中ns应设置为祖先元素(可能是文档根)中的xmlns="..."属性中指定的默认命名空间。

I'd suggest reading the LINQ to XML guide for more explanation of how to use the API.我建议阅读LINQ to XML 指南以获取有关如何使用 API 的更多说明。

You can use following class to deserialize the xml into C# class object and then easily can access any property to get desired value您可以使用以下类将 xml 反序列化为 C# 类对象,然后可以轻松访问任何属性以获得所需的值

POC Code:验证码:

[XmlRoot(ElementName="CollectionDetails")]
public class CollectionDetails {
    [XmlElement(ElementName="Collection")]
    public string Collection { get; set; }
    [XmlElement(ElementName="Year")]
    public string Year { get; set; }
    [XmlElement(ElementName="FilePreparationDate")]
    public string FilePreparationDate { get; set; }
}

[XmlRoot(ElementName="Source")]
public class Source {
    [XmlElement(ElementName="ProtectiveMarking")]
    public string ProtectiveMarking { get; set; }
    [XmlElement(ElementName="UKPRN")]
    public string UKPRN { get; set; }
    [XmlElement(ElementName="TransmissionType")]
    public string TransmissionType { get; set; }
    [XmlElement(ElementName="SoftwareSupplier")]
    public string SoftwareSupplier { get; set; }
    [XmlElement(ElementName="SoftwarePackage")]
    public string SoftwarePackage { get; set; }
    [XmlElement(ElementName="Release")]
    public string Release { get; set; }
    [XmlElement(ElementName="SerialNo")]
    public string SerialNo { get; set; }
    [XmlElement(ElementName="DateTime")]
    public string DateTime { get; set; }
}

[XmlRoot(ElementName="Header")]
public class Header {
    [XmlElement(ElementName="CollectionDetails")]
    public CollectionDetails CollectionDetails { get; set; }
    [XmlElement(ElementName="Source")]
    public Source Source { get; set; }
}

Sample code:示例代码:

XmlSerializer serializer = new XmlSerializer(typeof(Header));
StreamReader reader = new StreamReader(path);
var header = (Header)serializer.Deserialize(reader);
reader.Close();
//use the header object to access your data



Update Here's another way using xpath:更新这是使用 xpath 的另一种方法:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.XPath;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            XPathNavigator nav;
            XPathDocument docNav;
            string xPath;

            docNav = new XPathDocument(AppDomain.CurrentDomain.BaseDirectory + "test.xml");
            nav = docNav.CreateNavigator();
            xPath = "/Header/CollectionDetails/Year/text()";

            string value = nav.SelectSingleNode(xPath).Value;
            Console.WriteLine(value);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM