【问题标题】:How to read xml on the basis of name attribute and get value [duplicate]如何根据名称属性读取xml并获取值[重复]
【发布时间】:2015-05-19 13:03:27
【问题描述】:
<root>
    <Message type="sms">
        <Details locale="en" message-type="User.ResetPassword" />
        <Context>
            <Parameter name="Time" value=" 16:03:31" />
            <Parameter name="pswr" value="00" />
            <Parameter name="Date" value="18/12/2014" />
        </Context>
        <Receiver>+923328749199</Receiver>
    </Message>
</root>

如何阅读此文件?比如我想获取时间、密码和日期的值,还有receiver标签值。

【问题讨论】:

  • 你可以简单地编写代码来阅读这个文件吗?
  • 我完成了。 @Quadeer Hussain,

标签: c# xml


【解决方案1】:

你的班级将是这样的。

   /*------------------------------------------------------------------------------
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------*/

namespace AutoGeneratedCode
{

   /// 
   [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
   [System.SerializableAttribute()]
   [System.Diagnostics.DebuggerStepThroughAttribute()]
   [System.ComponentModel.DesignerCategoryAttribute("code")]
   [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
   [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
   public partial class root
   {
      private rootMessage messageField;
      /// 
      public rootMessage Message
      {
         get
         {
            return this.messageField;
         }
         set
         {
            this.messageField = value;
         }
      }
   }
   /// 
   [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
   [System.SerializableAttribute()]
   [System.Diagnostics.DebuggerStepThroughAttribute()]
   [System.ComponentModel.DesignerCategoryAttribute("code")]
   [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
   public partial class rootMessage
   {
      private rootMessageDetails detailsField;
      private rootMessageParameter[] contextField;
      private decimal receiverField;
      private string typeField;
      /// 
      public rootMessageDetails Details
      {
         get
         {
            return this.detailsField;
         }
         set
         {
            this.detailsField = value;
         }
      }
      /// 
      [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable=false)]
      public rootMessageParameter[] Context
      {
         get
         {
            return this.contextField;
         }
         set
         {
            this.contextField = value;
         }
      }
      /// 
      public decimal Receiver
      {
         get
         {
            return this.receiverField;
         }
         set
         {
            this.receiverField = value;
         }
      }
      /// 
      [System.Xml.Serialization.XmlAttributeAttribute()]
      public string type
      {
         get
         {
            return this.typeField;
         }
         set
         {
            this.typeField = value;
         }
      }
   }
   /// 
   [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
   [System.SerializableAttribute()]
   [System.Diagnostics.DebuggerStepThroughAttribute()]
   [System.ComponentModel.DesignerCategoryAttribute("code")]
   [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
   public partial class rootMessageDetails
   {
      private string localeField;
      private string messagetypeField;
      /// 
      [System.Xml.Serialization.XmlAttributeAttribute()]
      public string locale
      {
         get
         {
            return this.localeField;
         }
         set
         {
            this.localeField = value;
         }
      }
      /// 
      [System.Xml.Serialization.XmlAttributeAttribute("message-type")]
      public string messagetype
      {
         get
         {
            return this.messagetypeField;
         }
         set
         {
            this.messagetypeField = value;
         }
      }
   }
   /// 
   [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
   [System.SerializableAttribute()]
   [System.Diagnostics.DebuggerStepThroughAttribute()]
   [System.ComponentModel.DesignerCategoryAttribute("code")]
   [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
   public partial class rootMessageParameter
   {
      private string nameField;
      private System.DateTime valueField;
      private bool valueFieldSpecified;
      /// 
      [System.Xml.Serialization.XmlAttributeAttribute()]
      public string name
      {
         get
         {
            return this.nameField;
         }
         set
         {
            this.nameField = value;
         }
      }
      /// 
      [System.Xml.Serialization.XmlAttributeAttribute()]
      public System.DateTime value
      {
         get
         {
            return this.valueField;
         }
         set
         {
            this.valueField = value;
         }
      }
      /// 
      [System.Xml.Serialization.XmlIgnoreAttribute()]
      public bool valueSpecified
      {
         get
         {
            return this.valueFieldSpecified;
         }
         set
         {
            this.valueFieldSpecified = value;
         }
      }
   }
}

在你的代码反序列化之后

var serializer = new XmlSerializer(typeof(root));

using (var file = File.OpenText("sample.xml"))
{
    root data = (root)serializer.Deserialize(file);

    // ... 
}

您可以使用数据通过根对象到达所有成员。

【讨论】:

    【解决方案2】:

    使用XDocument

    这是我的解决方案:

    如果您的 xml 来自 URL,请使用 XDocument.Load(/URL/)

    var xml = "<root><Message type='sms'><Details locale='en' message-type='User.ResetPassword' /><Context><Parameter name='Time' value=' 16:03:31' /><Parameter name='pswr' value='00' /><Parameter name='Date' value='18/12/2014' /></Context><Receiver>+923328749199</Receiver></Message></root>";
    var document = XDocument.Parse(xml);
    
    var messages = document.Root.Elements();
    foreach (var message in messages)
    {
        var context = message.Element("Context");
        var parameters = context.Elements("Parameter");
        foreach (var parameter in parameters)
        {
            var name = parameter.Attribute("name").Value;
            var value = parameter.Attribute("value").Value;
    
            Console.WriteLine ("Parameter {0} with value of {1}", name, value);
        }
    
        Console.WriteLine ("Receiver {0}", message.Element("Receiver").Value);
    }
    

    输出

    Parameter Time with value of  16:03:31
    Parameter pswr with value of 00
    Parameter Date with value of 18/12/2014
    Receiver +923328749199
    

    【讨论】:

      【解决方案3】:

      希望有帮助........

      Dim Xdoc As XDocument
          Xdoc = XDocument.Parse(pstrXmlInput)
          Dim Tktno = From Attbvalue In Xdoc.Descendants("Context").Elements("Parameter").Attributes("value")
                      Select Attbvalue.Value
      

      【讨论】:

      • 谢谢,但它给我的错误数据在根级别是无效的
      • @QadeerHussain 在这种情况下,您的 XML 无效......这意味着它与您在问题中提出的 XML 不匹配。
      • 你尝试相同的 xml 文件并尝试在 xdoc 上调试,看看你得到了什么 xml
      • XDocument Xdoc = XDocument.Parse("C:\\Users\\qadeer.hussain\\Desktop\\gw-msg-2.xml"); var y = from nm in Xdoc.Descendants("Context").Elements("Parameter").Attributes("value") select nm.Value; Response.Write(y.Count());
      • 我正在尝试解析我的代码在上面发布的相同 xml
      猜你喜欢
      • 2011-07-27
      • 2012-08-13
      • 2021-12-03
      • 1970-01-01
      • 2023-03-13
      • 2010-10-29
      • 1970-01-01
      相关资源
      最近更新 更多