如何使用下面的代码通过XML中的键读取值?

时间:2013-06-09 21:03:47

标签: xml vb.net xml-serialization

XML文件:

<providers>
  <provider>
    <name>Gmail</name>
    <domain>gmail.com</domain>
    <smtp>smtp.gmail.com</smtp>
    <ssl>true</ssl>
    <smtpport></smtpport>
    <sslport>587</sslport>
  </provider>
  <provider>
    <name>Outlook</name>
    <domain>live.com</domain>
    <smtp>smtp.live.com</smtp>
    <ssl>true</ssl>
    <sslport>587</sslport>
    <smtpport></smtpport>
  </provider>
</providers>

C#来源

// ------------------------------------------------------------------------------
//  <auto-generated>
//    Generated by Xsd2Code. Version 3.4.0.38967
//    <NameSpace>Test</NameSpace><Collection>IList</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>False</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>False</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><EnableEncoding>True</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>False</ExcludeIncludedTypes><EnableInitializeFields>True</EnableInitializeFields>
//  </auto-generated>
// ------------------------------------------------------------------------------
namespace Test
{
    using System;
    using System.Diagnostics;
    using System.Xml.Serialization;
    using System.Collections;
    using System.Xml.Schema;
    using System.ComponentModel;
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Collections.Generic;


    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.233")]
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class Providers
    {

        private IList<ProvidersProvider> providerField;

        private static System.Xml.Serialization.XmlSerializer serializer;

        public Providers()
        {
            this.providerField = new List<ProvidersProvider>();
        }

        [System.Xml.Serialization.XmlElementAttribute("Provider", Order = 0)]
        public IList<ProvidersProvider> Provider
        {
            get
            {
                return this.providerField;
            }
            set
            {
                this.providerField = value;
            }
        }

        private static System.Xml.Serialization.XmlSerializer Serializer
        {
            get
            {
                if ((serializer == null))
                {
                    serializer = new System.Xml.Serialization.XmlSerializer(typeof(Providers));
                }
                return serializer;
            }
        }

        #region Serialize/Deserialize
        /// <summary>
        /// Serializes current Providers object into an XML document
        /// </summary>
        /// <returns>string XML value</returns>
        public virtual string Serialize(System.Text.Encoding encoding)
        {
            System.IO.StreamReader streamReader = null;
            System.IO.MemoryStream memoryStream = null;
            try
            {
                memoryStream = new System.IO.MemoryStream();
                System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
                xmlWriterSettings.Encoding = encoding;
                System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
                Serializer.Serialize(xmlWriter, this);
                memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                streamReader = new System.IO.StreamReader(memoryStream);
                return streamReader.ReadToEnd();
            }
            catch (Exception ex) {
                System.Windows.Forms.MessageBox.Show(ex.StackTrace );
                return "";
            }
            finally
            {
                if ((streamReader != null))
                {
                    streamReader.Dispose();
                }
                if ((memoryStream != null))
                {
                    memoryStream.Dispose();
                }
            }
        }

        public virtual string Serialize()
        {
            return Serialize(Encoding.UTF8);
        }

        /// <summary>
        /// Deserializes workflow markup into an Providers object
        /// </summary>
        /// <param name="xml">string workflow markup to deserialize</param>
        /// <param name="obj">Output Providers object</param>
        /// <param name="exception">output Exception value if deserialize failed</param>
        /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
        public static bool Deserialize(string xml, out Providers obj, out System.Exception exception)
        {
            exception = null;
            obj = default(Providers);
            try
            {
                obj = Deserialize(xml);
                return true;
            }
            catch (System.Exception ex)
            {
                exception = ex;

                System.Windows.Forms.MessageBox.Show(ex.StackTrace );
                return false;
            }
        }

        public static bool Deserialize(string xml, out Providers obj)
        {
            System.Exception exception = null;
            return Deserialize(xml, out obj, out exception);
        }

        public static Providers Deserialize(string xml)
        {
            System.IO.StringReader stringReader = null;
            try
            {
                System.Windows.Forms.MessageBox.Show(xml);
                stringReader = new System.IO.StringReader(xml);
                return ((Providers)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.StackTrace);
                return null;
            }
            finally
            {
                if ((stringReader != null))
                {
                    stringReader.Dispose();
                }
            }
        }

        /// <summary>
        /// Serializes current Providers object into file
        /// </summary>
        /// <param name="fileName">full path of outupt xml file</param>
        /// <param name="exception">output Exception value if failed</param>
        /// <returns>true if can serialize and save into file; otherwise, false</returns>
        public virtual bool SaveToFile(string fileName, System.Text.Encoding encoding, out System.Exception exception)
        {
            exception = null;
            try
            {
                SaveToFile(fileName, encoding);
                return true;
            }
            catch (System.Exception e)
            {
                exception = e;

                System.Windows.Forms.MessageBox.Show(e.StackTrace );

                return false;
            }
        }

        public virtual bool SaveToFile(string fileName, out System.Exception exception)
        {
            return SaveToFile(fileName, Encoding.UTF8, out exception);
        }

        public virtual void SaveToFile(string fileName)
        {
            SaveToFile(fileName, Encoding.UTF8);
        }

        public virtual void SaveToFile(string fileName, System.Text.Encoding encoding)
        {
            System.IO.StreamWriter streamWriter = null;
            try
            {
                string xmlString = Serialize(encoding);
                streamWriter = new System.IO.StreamWriter(fileName, false, Encoding.UTF8);
                streamWriter.WriteLine(xmlString);
                streamWriter.Close();
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.StackTrace);
                return ;
            }
            finally
            {
                if ((streamWriter != null))
                {
                    streamWriter.Dispose();
                }
            }
        }

        /// <summary>
        /// Deserializes xml markup from file into an Providers object
        /// </summary>
        /// <param name="fileName">string xml file to load and deserialize</param>
        /// <param name="obj">Output Providers object</param>
        /// <param name="exception">output Exception value if deserialize failed</param>
        /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
        public static bool LoadFromFile(string fileName, System.Text.Encoding encoding, out Providers obj, out System.Exception exception)
        {
            exception = null;
            obj = default(Providers);
            try
            {
                obj = LoadFromFile(fileName, encoding);
                return true;
            }
            catch (System.Exception ex)
            {
                exception = ex;
                System.Windows.Forms.MessageBox.Show(ex.StackTrace );
                return false;
            }
        }

        public static bool LoadFromFile(string fileName, out Providers obj, out System.Exception exception)
        {
            return LoadFromFile(fileName, Encoding.UTF8, out obj, out exception);
        }

        public static bool LoadFromFile(string fileName, out Providers obj)
        {
            System.Exception exception = null;
            return LoadFromFile(fileName, out obj, out exception);
        }

        public static Providers LoadFromFile(string fileName)
        {
            return LoadFromFile(fileName, Encoding.UTF8);
        }

        public static Providers LoadFromFile(string fileName, System.Text.Encoding encoding)
        {
            System.IO.FileStream file = null;
            System.IO.StreamReader sr = null;
            try
            {
                file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
                sr = new System.IO.StreamReader(file, encoding);
                string xmlString = sr.ReadToEnd();
                sr.Close();
                file.Close();
                return Deserialize(xmlString);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.StackTrace);
                return null;
            }
            finally
            {
                if ((file != null))
                {
                    file.Dispose();
                }
                if ((sr != null))
                {
                    sr.Dispose();
                }
            }
        }
        #endregion
    }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.233")]
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class ProvidersProvider
    {

        private IList<string> itemsField;

        private IList<ItemsChoiceType> itemsElementNameField;

        private static System.Xml.Serialization.XmlSerializer serializer;

        public ProvidersProvider()
        {
            this.itemsElementNameField = new List<ItemsChoiceType>();
            this.itemsField = new List<string>();
        }

        [System.Xml.Serialization.XmlElementAttribute("domain", typeof(string), Order = 0)]
        [System.Xml.Serialization.XmlElementAttribute("name", typeof(string), Order = 0)]
        [System.Xml.Serialization.XmlElementAttribute("smtp", typeof(string), Order = 0)]
        [System.Xml.Serialization.XmlElementAttribute("smtpport", typeof(string), Order = 0)]
        [System.Xml.Serialization.XmlElementAttribute("ssl", typeof(string), Order = 0)]
        [System.Xml.Serialization.XmlElementAttribute("sslport", typeof(string), Order = 0)]
        [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
        public IList<string> Items
        {
            get
            {
                return this.itemsField;
            }
            set
            {
                this.itemsField = value;
            }
        }

        [System.Xml.Serialization.XmlElementAttribute("ItemsElementName", Order = 1)]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public IList<ItemsChoiceType> ItemsElementName
        {
            get
            {
                return this.itemsElementNameField;
            }
            set
            {
                this.itemsElementNameField = value;
            }
        }

        private static System.Xml.Serialization.XmlSerializer Serializer
        {
            get
            {
                if ((serializer == null))
                {
                    serializer = new System.Xml.Serialization.XmlSerializer(typeof(ProvidersProvider));
                }
                return serializer;
            }
        }

        #region Serialize/Deserialize
        /// <summary>
        /// Serializes current ProvidersProvider object into an XML document
        /// </summary>
        /// <returns>string XML value</returns>
        public virtual string Serialize(System.Text.Encoding encoding)
        {
            System.IO.StreamReader streamReader = null;
            System.IO.MemoryStream memoryStream = null;
            try
            {
                memoryStream = new System.IO.MemoryStream();
                System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
                xmlWriterSettings.Encoding = encoding;
                System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
                Serializer.Serialize(xmlWriter, this);
                memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                streamReader = new System.IO.StreamReader(memoryStream);
                return streamReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.StackTrace);
                return "";
            }
            finally
            {
                if ((streamReader != null))
                {
                    streamReader.Dispose();
                }
                if ((memoryStream != null))
                {
                    memoryStream.Dispose();
                }
            }
        }

        public virtual string Serialize()
        {
            return Serialize(Encoding.UTF8);
        }

        /// <summary>
        /// Deserializes workflow markup into an ProvidersProvider object
        /// </summary>
        /// <param name="xml">string workflow markup to deserialize</param>
        /// <param name="obj">Output ProvidersProvider object</param>
        /// <param name="exception">output Exception value if deserialize failed</param>
        /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
        public static bool Deserialize(string xml, out ProvidersProvider obj, out System.Exception exception)
        {
            exception = null;
            obj = default(ProvidersProvider);
            try
            {
                obj = Deserialize(xml);
                return true;
            }
            catch (System.Exception ex)
            {
                exception = ex;

                System.Windows.Forms.MessageBox.Show(ex.StackTrace );

                return false;
            }
        }

        public static bool Deserialize(string xml, out ProvidersProvider obj)
        {
            System.Exception exception = null;
            return Deserialize(xml, out obj, out exception);
        }

        public static ProvidersProvider Deserialize(string xml)
        {
            System.IO.StringReader stringReader = null;
            try
            {
                stringReader = new System.IO.StringReader(xml);
                return ((ProvidersProvider)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.StackTrace);
                return null;
            }
            finally
            {
                if ((stringReader != null))
                {
                    stringReader.Dispose();
                }
            }
        }

        /// <summary>
        /// Serializes current ProvidersProvider object into file
        /// </summary>
        /// <param name="fileName">full path of outupt xml file</param>
        /// <param name="exception">output Exception value if failed</param>
        /// <returns>true if can serialize and save into file; otherwise, false</returns>
        public virtual bool SaveToFile(string fileName, System.Text.Encoding encoding, out System.Exception exception)
        {
            exception = null;
            try
            {
                SaveToFile(fileName, encoding);
                return true;
            }
            catch (System.Exception e){

                System.Windows.Forms.MessageBox.Show(e.StackTrace );

                exception = e;
                return false;
            }
        }

        public virtual bool SaveToFile(string fileName, out System.Exception exception)
        {
            return SaveToFile(fileName, Encoding.UTF8, out exception);
        }

        public virtual void SaveToFile(string fileName)
        {
            SaveToFile(fileName, Encoding.UTF8);
        }

        public virtual void SaveToFile(string fileName, System.Text.Encoding encoding)
        {
            System.IO.StreamWriter streamWriter = null;
            try
            {
                string xmlString = Serialize(encoding);
                streamWriter = new System.IO.StreamWriter(fileName, false, Encoding.UTF8);
                streamWriter.WriteLine(xmlString);
                streamWriter.Close();
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.StackTrace);
                return;
            }
            finally
            {
                if ((streamWriter != null))
                {
                    streamWriter.Dispose();
                }
            }
        }

        /// <summary>
        /// Deserializes xml markup from file into an ProvidersProvider object
        /// </summary>
        /// <param name="fileName">string xml file to load and deserialize</param>
        /// <param name="obj">Output ProvidersProvider object</param>
        /// <param name="exception">output Exception value if deserialize failed</param>
        /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
        public static bool LoadFromFile(string fileName, System.Text.Encoding encoding, out ProvidersProvider obj, out System.Exception exception)
        {
            exception = null;
            obj = default(ProvidersProvider);
            try
            {
                obj = LoadFromFile(fileName, encoding);
                return true;
            }
            catch (System.Exception ex)
            {

                System.Windows.Forms.MessageBox.Show(ex.StackTrace );

                exception = ex;
                return false;
            }
        }

        public static bool LoadFromFile(string fileName, out ProvidersProvider obj, out System.Exception exception)
        {
            return LoadFromFile(fileName, Encoding.UTF8, out obj, out exception);
        }

        public static bool LoadFromFile(string fileName, out ProvidersProvider obj)
        {
            System.Exception exception = null;
            return LoadFromFile(fileName, out obj, out exception);
        }

        public static ProvidersProvider LoadFromFile(string fileName)
        {
            return LoadFromFile(fileName, Encoding.UTF8);
        }

        public static ProvidersProvider LoadFromFile(string fileName, System.Text.Encoding encoding)
        {
            System.IO.FileStream file = null;
            System.IO.StreamReader sr = null;
            try
            {
                file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
                sr = new System.IO.StreamReader(file, encoding);
                string xmlString = sr.ReadToEnd();
                sr.Close();
                file.Close();
                return Deserialize(xmlString);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.StackTrace);
                return null;
            }
            finally
            {
                if ((file != null))
                {
                    file.Dispose();
                }
                if ((sr != null))
                {
                    sr.Dispose();
                }
            }
        }
        #endregion
    }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.233")]
    [System.SerializableAttribute()]
    [System.Xml.Serialization.XmlTypeAttribute(IncludeInSchema = false)]
    public enum ItemsChoiceType
    {

        /// <remarks/>
        domain,

        /// <remarks/>
        name,

        /// <remarks/>
        smtp,

        /// <remarks/>
        smtpport,

        /// <remarks/>
        ssl,

        /// <remarks/>
        sslport,
    }
}

我想通过传递参数“domain”来读取XML并获取“ssl”字段 一个方法。我尝试了下面的代码,但发生了异常。这是我第一次使用 这种从xml中获取价值的方法,有人可以给出一些如何获得它的建议吗?

        Dim providers As New Providers()
        Dim ex As New Exception
        Dim provider As ProvidersProvider = New ProvidersProvider()

        provider.ItemsElementName.Add(ItemsChoiceType.domain)
        provider.Items.Add("google.com")

        provider.ItemsElementName.Add(ItemsChoiceType.name)
        provider.Items.Add("Google")

        'provider.Items(ItemsChoiceType.domain) = "google.com"
        'provider.Items(ItemsChoiceType.name) = "Google"
        'provider.Items(ItemsChoiceType.ssl) = "0"
        'provider.Items(ItemsChoiceType.sslport) = "467"
        'provider.Items(ItemsChoiceType.smtp) = "smtp.gmail.com"
        'provider.Items(ItemsChoiceType.smtpport) = "123"

        providers.Provider.Add(provider)
        providers.SaveToFile("C:\Test.xml")

        Try
            If Not providers.LoadFromFile(Path.Combine(Globle.DllFolder, "Test.xml"), providers, ex) Then
                MsgBox("Test.xml error" & ex.StackTrace, MsgBoxStyle.Critical, Constant.MSGBOX_TITLE)
                Exit Sub
            End If
        Catch exp As Exception
            MsgBox(exp.StackTrace())
        End Try


        Dim providerList As New List(Of ProvidersProvider)

        For Each p As ProvidersProvider In providerList

            Dim domain As String = p.Items(ItemsChoiceType.domain)

            Dim mailDomain As String = Mid(Me.TextBoxMailAddress.Text, Me.TextBoxMailAddress.Text.IndexOf("@"))

            If domain.Equals(mailDomain) Then
                MsgBox("p.Items(ItemsChoiceType.sslport):" + p.Items(ItemsChoiceType.sslport))
            End If

        Next
    End If

例外:

   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)

   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, RecursionLimiter limiter)

   at System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModel model, XmlRootAttribute root, String defaultNamespace, RecursionLimiter limiter)

   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)

   at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)

   at System.Xml.Serialization.XmlSerializer..ctor(Type type)

1 个答案:

答案 0 :(得分:0)

基于域获取SSL值的方法。您将域作为参数传递

public string GetSSL(string domain)
{

    var doc = XDocument.Load(@"c:\tmp\test.xml");
    var result = doc.Descendants("provider")
                 .Where(x=>x.Element("domain").Value == domain)
                 .Select(x=>x.Element("ssl").Value);

    return result.FirstOrDefault();
}

使用示例

Console.WriteLine(GetSSL("live.com"));

修改

我刚注意到你是一个VB人,这在VB中是一样的

public Function GetSSL(domain as string) as string

    Dim doc = XDocument.Load("c:\tmp\test.xml")
    Dim result = from i in doc.Descendants("provider") where i.Element("domain").Value = domain
                    select i.Element("ssl").Value

    return result.FirstOrDefault()
End Function