Get Value from XML tag - c#

I have the following code:
p.tel.FirstOrDefault(t => t.teltype == "mobile").ToString()
<person>
<name>Donald Duck</name>
<tel teltype="voice" />
<tel teltype="mobile">01000000</tel>
</person>
The c# class for the xml look like this:
[System.Xml.Serialization.XmlElementAttribute("tel")]
public enterprisePersonTel[] tel {
get {
return this.telField;
}
set {
this.telField = value;
}
}
My code returns: enterprisePersonTel
This doesn't work
p.tel.FirstOrDefault(t => t.teltype == "mobile").Value
How can I get the actual telephone number?

The class for the attribute was not generated correctly
public partial class enterprisePersonTel
{
private string teltypeField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string teltype
{
get
{
return this.teltypeField;
}
set
{
this.teltypeField = value;
}
}
/// <remarks/>
**[System.Xml.Serialization.XmlTextAttribute()]
public string Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}**
}
The ** part of the text was missing when using paste as class in Visual studio.

Related

How to deserialize XML document with inner tags and inner elements?

This is my XML file.
<getMetadata>
<Project Name="Doors_Demo">
<Module FullPath="/Doors_Demo/Test_Module2">
<Attributes>
<Attribute name="TableType" type="TableType" />
<Attribute name="TableTopBorder" type="TableEdgeType" />
</Attributes>
</Module>
</Project>
</getMetadata>
I want to deserialize the above XML
Below is my code:
[XmlRoot("getMetadata")]
public class RootClass
{
public Project element_Project;
[XmlElement("Project")]
public Project Project
{
get { return element_Project; }
set { element_Project = value; }
}
}
public class Project
{
public string name;
[XmlAttribute("Name")]
public string Id
{
get { return name; }
set { name = value; }
}
}
public static void Main(string[] args)
{
RootClass obj = new RootClass();
XmlSerializer serializer = new XmlSerializer(typeof(RootClass));
using (FileStream stream = new FileStream(#"E:\getMetadata(4).xml", FileMode.Open))
{
RootClass myxml = (RootClass)serializer.Deserialize(stream);
Console.WriteLine(myxml.Project.name);
}
}
I want to deserialize my XML into a list, I am not able to access all inner elements and attributes inside the root element.
I want details of module element and its inner elements and tags into list which can be accessed.
Here is a little trick to generate classes from your XML automatically.
First, create a new empty class, name it for example TempXml.
Copy your XML to the clipboard and open the new empty class you just created.
Go to Visual Studio Edit menu then Paste Special and Paste XML as Classes:
This will generate the following code:
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class getMetadata
{
private getMetadataProject projectField;
/// <remarks/>
public getMetadataProject Project
{
get
{
return this.projectField;
}
set
{
this.projectField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProject
{
private getMetadataProjectModule moduleField;
private string nameField;
/// <remarks/>
public getMetadataProjectModule Module
{
get
{
return this.moduleField;
}
set
{
this.moduleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProjectModule
{
private getMetadataProjectModuleAttribute[] attributesField;
private string fullPathField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Attribute", IsNullable = false)]
public getMetadataProjectModuleAttribute[] Attributes
{
get
{
return this.attributesField;
}
set
{
this.attributesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string FullPath
{
get
{
return this.fullPathField;
}
set
{
this.fullPathField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProjectModuleAttribute
{
private string nameField;
private string typeField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
}
Which should work fine with the XmlSerializer class.
You can clean up a little bit the generated output by removing the empty remarks, changing the name of the classes to use camel case (in this case you need to specify the real element name in the attribute as you were doing in your question) or move the classes to different files.
Hope it helps.

How to deserialize element that can be single or array?

Got XML that i want to deserialize to Object.
There is no questions if i deserialize only non-multiple value element, but i got no idea what to do with an array of value elements in value element.
There is always UnknownNode with LocalName = #text,
XML to deserialize
<?xml version="1.0" encoding="UTF-8"?>
<issue>
<custom_fields type="array">
<custom_field id="11" name="Version">
<value>7.9.18.31</value>
</custom_field>
<custom_field id="89" name="Tags" multiple="true">
<value type="array">
<value>Tag1</value>
<value>Tag3</value>
<value>Tag6</value>
</value>
</custom_field>
<custom_field id="90" name="started_on">
<value>2017-08-25</value>
</custom_field>
</custom_fields>
</issue>
class i get with xsd.exe
using System.Xml.Serialization;
[XmlRoot(IsNullable=false)]
public partial class issue
{
private object[] itemsField;
[XmlElement("custom_fields", typeof(issueCustom_fields))]
[XmlElement("value", typeof(Value))]
public object[] Items
{
get { return itemsField; }
set { itemsField = value; }
}
}
public class Value
{
private Value[] valueField;
private string typeField;
[XmlElement("value")]
public Value[] value
{
get { return valueField; }
set { valueField = value; }
}
[XmlAttribute]
public string type
{
get { return typeField; }
set { typeField = value; }
}
}
public class issueCustom_fields
{
private issueCustom_fieldsCustom_field[] custom_fieldField;
private string typeField;
[XmlElement("custom_field")]
public issueCustom_fieldsCustom_field[] custom_field
{
get { return custom_fieldField; }
set { custom_fieldField = value; }
}
[XmlAttribute]
public string type
{
get { return typeField; }
set { typeField = value; }
}
}
public class issueCustom_fieldsCustom_field
{
private Value[] valueField;
private string idField;
private string nameField;
private string multipleField;
[XmlElement("value")]
public Value[] value
{
get { return valueField; }
set { valueField = value; }
}
[XmlAttribute]
public string id
{
get { return idField; }
set { idField = value; }
}
[XmlAttribute]
public string name
{
get { return nameField; }
set { nameField = value; }
}
[XmlAttribute]
public string multiple
{
get { return multipleField; }
set { multipleField = value; }
}
}
Deserializing code
var ser = new XmlSerializer(typeof(issue));
var issue = new issue();
using (var sr = new StreamReader("testIssues.xml"))
issue = (issue)ser.Deserialize(sr);
i can get data using:
ser.UnknownNode += (s, ea) =>
{
if (ea.LocalName == "#text" && ea.ObjectBeingDeserialized is Value)
{
Value val = (Value)ea.ObjectBeingDeserialized;
if (val.value == null)
{
val.Val = ea.Text;
}
}
};
but is there a way to get it more smoothe way using just deserialization?
Have you tried to use XmlArrayAttribute?
[XmlArray("value")]
public Value[] Items
{
get { return itemsField; }
set { itemsField = value; }
}
[XmlType("Value")]
public class Value
{
....
}
Check out this question.

Missing properties in instance of class

I'm writing generic method in Android app, and I have a problem with missing properties.
My class has 7 public properties but when I'm trying to get all properties I'm getting list with one property.
Here is my code:
T item = (T)Activator.CreateInstance(typeof(T));
var properties = item.GetType().GetProperties();
Problem occurs in all classes.
I have the same code (also the same classes) in similar application for iOS and everything works fine.
Here is sample class:
public partial class DB_USER {
private int iD_USERField;
private int iD_ACTORField;
private System.Nullable<long> iD_DISTRIBUTORField;
private string lOGINField;
private string pASSWORDField;
private bool iS_BLOCKEDField;
private string dESCRIPTIONField;
/// <remarks/>
public int ID_USER {
get {
return this.iD_OPERATORField;
}
set {
this.iD_OPERATORField = value;
}
}
/// <remarks/>
public int ID_ACTOR {
get {
return this.iD_ACTORField;
}
set {
this.iD_ACTORField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
public System.Nullable<long> ID_DISTRIBUTOR {
get {
return this.iD_DISTRIBUTORField;
}
set {
this.iD_DISTRIBUTORField = value;
}
}
/// <remarks/>
public string LOGIN {
get {
return this.lOGINField;
}
set {
this.lOGINField = value;
}
}
/// <remarks/>
public string PASSWORD {
get {
return this.pASSWORDField;
}
set {
this.pASSWORDField = value;
}
}
/// <remarks/>
public bool IS_BLOCKED {
get {
return this.iS_BLOCKEDField;
}
set {
this.iS_BLOCKEDField = value;
}
}
/// <remarks/>
public string DESCRIPTION {
get {
return this.dESCRIPTIONField;
}
set {
this.dESCRIPTIONField = value;
}
}
}

Error while reading a Array from C# assembly registered as COM in VBScript

I have used the xsd.exe program to create a class hierarchy for a xsd file. I am successfully able to deserialize a xml file and read values from it in C#. However when i register the library and am trying to read array values from VBScript it fails.
I get Wrong number of arguments or invalid property assignment error. I am however able to read the values of simple properties.
Here is my class hierarchy
using System.Xml.Serialization;
public partial class AppEntryDefinition {
private ProductDefinition productDefinitionField;
private ViewSection[] viewDefinitionField;
public ProductDefinition productDefinition {
get {
return this.productDefinitionField;
}
set {
this.productDefinitionField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("viewSection", IsNullable=false)]
public ViewSection[] viewDefinition {
get {
return this.viewDefinitionField;
}
set {
this.viewDefinitionField = value;
}
}
}
public partial class ProductDefinition {
private int kindCodeField;
private string productCodeField;
private string productTitleField;
private string adminSystemField;
private string vapCodeField;
private Features featuresField;
private RuleSet[] ruleSetField;
/// <remarks/>
public int kindCode {
get {
return this.kindCodeField;
}
set {
this.kindCodeField = value;
}
}
/// <remarks/>
public string productCode {
get {
return this.productCodeField;
}
set {
this.productCodeField = value;
}
}
/// <remarks/>
public string productTitle {
get {
return this.productTitleField;
}
set {
this.productTitleField = value;
}
}
/// <remarks/>
public string adminSystem {
get {
return this.adminSystemField;
}
set {
this.adminSystemField = value;
}
}
/// <remarks/>
public string vapCode {
get {
return this.vapCodeField;
}
set {
this.vapCodeField = value;
}
}
/// <remarks/>
public Features features {
get {
return this.featuresField;
}
set {
this.featuresField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ruleSet")]
public RuleSet[] ruleSet {
get {
return this.ruleSetField;
}
set {
this.ruleSetField = value;
}
}
}
public partial class RuleSet {
private Rule[] ruleField;
private string phaseField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("rule")]
public Rule[] rule {
get {
return this.ruleField;
}
set {
this.ruleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string phase {
get {
return this.phaseField;
}
set {
this.phaseField = value;
}
}
}
public partial class Rule {
private Case[] caseField;
private string nameField;
private string typeField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("case")]
public Case[] #case {
get {
return this.caseField;
}
set {
this.caseField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
}
Here is my code which deserializes my xml to objects
namespace CustomUtilities
{
public class XmlSerializer
{
public AppEntryDefinition Deserialize(String xmlPath)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(AppEntryDefinition));
AppEntryDefinition aed = null;
aed = (AppEntryDefinition)serializer.Deserialize(new System.IO.StreamReader(xmlPath));
return aed;
}
}
}
Here is my vbscript code
Dim obj, objAppEntry
Set obj = CreateObject("CustomUtilities.XmlSerializer")
Set objAppEntry = obj.Deserialize("C:\Users\xx\Desktop\schema\xx.xml")
Set xxx = objAppEntry.productDefinition.ruleSet
Yes, these arrays will not get through from NET to VBScript as they are not COM automation compatible.
What you can do, though, is create a partial class with the same name as the initial one, duplicate the array properties, give them another name, and declare them as a type that can be used in automation (and recompile the whole thing). You could create a custom type (it's necessary if yuo don't want to duplicate the values), but the easiest way to do it is to reuse the "old" ArrayList class. It's marked as COM visible and it can be used easily from a script language.
So here is a sample partial add-on:
public partial class ProductDefinition
{
[XmlIgnore]
public ArrayList ruleSetArrayList
{
get
{
return new ArrayList(ruleSet);
}
}
}
And the script that uses it:
Set xxx = objAppEntry.productDefinition.ruleSetArrayList
for each item in xxx
WScript.echo item.phase
next

How to get value from element attribute, XML Serialization

I want to get an attribute from vimeo xml.. here is structure of xml document
<?xml version="1.0" encoding="UTF-8" ?>
- <rsp generated_in="0.6533" stat="ok">
- <videos on_this_page="15" page="1" perpage="15" total="329">
- <video allow_adds="1" embed_privacy="anywhere" id="3475223" is_hd="0" is_transcoding="0" license="0" privacy="anybody">
<title>AxDroid - Android on Dell Axim x51v</title>
<description>This is my first attempt at installing and running Android on my Dell Axim x51v. Touchscreen and buttons are working! For details please visit: http://axdroid.blogspot.com/</description>
<upload_date>2009-03-04 16:14:19</upload_date>
<modified_date>2012-07-14 07:03:32</modified_date>
<number_of_likes>2</number_of_likes>
<number_of_plays>43422</number_of_plays>
<number_of_comments>1</number_of_comments>
<width>320</width>
<height>240</height>
<duration>320</duration>
- <owner display_name="Ertan D." id="1387509" is_plus="0" is_pro="0" is_staff="0" profileurl="http://vimeo.com/user1387509" realname="Ertan D." username="user1387509" videosurl="http://vimeo.com/user1387509/videos">
- <portraits>
<portrait height="30" width="30">http://a.vimeocdn.com/images_v6/portraits/portrait_30_yellow.png</portrait>
<portrait height="75" width="75">http://a.vimeocdn.com/images_v6/portraits/portrait_75_yellow.png</portrait>
<portrait height="100" width="100">http://a.vimeocdn.com/images_v6/portraits/portrait_100_yellow.png</portrait>
<portrait height="300" width="300">http://a.vimeocdn.com/images_v6/portraits/portrait_300_yellow.png</portrait>
</portraits>
</owner>
- <tags>
<tag author="1387509" id="8397224" normalized="android" url="http://vimeo.com/tag:android">android</tag>
<tag author="1387509" id="8397225" normalized="dell" url="http://vimeo.com/tag:dell">dell</tag>
<tag author="1387509" id="8397226" normalized="axim" url="http://vimeo.com/tag:axim">axim</tag>
<tag author="1387509" id="8397227" normalized="linux" url="http://vimeo.com/tag:linux">linux</tag>
<tag author="1387509" id="8397228" normalized="google" url="http://vimeo.com/tag:google">google</tag>
<tag author="1387509" id="8397229" normalized="pda" url="http://vimeo.com/tag:pda">pda</tag>
<tag author="1387509" id="8397230" normalized="ppc" url="http://vimeo.com/tag:ppc">ppc</tag>
</tags>
- <cast>
<member display_name="Ertan D." id="1387509" role="" username="user1387509" />
</cast>
- <urls>
<url type="video">http://vimeo.com/3475223</url>
</urls>
- <thumbnails>
<thumbnail height="75" width="100">http://b.vimeocdn.com/ts/347/807/3478071_100.jpg</thumbnail>
<thumbnail height="150" width="200">http://b.vimeocdn.com/ts/347/807/3478071_200.jpg</thumbnail>
<thumbnail height="480" width="640">http://b.vimeocdn.com/ts/347/807/3478071_640.jpg</thumbnail>
</thumbnails>
</video>
- <video allow_adds="1" embed_privacy="anywhere" id="28665952" is_hd="1" is_transcoding="0" license="0" privacy="anybody">
<title>Duygu + Ertan Şıkır Şıkır by DÜĞÜNHİKAYEMİZ</title>
<description />
<upload_date>2011-09-06 10:54:49</upload_date>
<modified_date>2012-07-14 06:41:33</modified_date>
<number_of_likes>3</number_of_likes>
<number_of_plays>26214</number_of_plays>
and I want to get username attribute from owner element. Here is serialization code.
[XmlTypeAttribute(AnonymousType = true)]
[XmlRootAttribute(Namespace = "", IsNullable = false, ElementName = "rsp")]
public partial class VimeoSearchResponse
{
private SearchResponseVideosWrapper _videos;
private string _generated_in;
private string _stat;
[XmlElementAttribute("videos", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public SearchResponseVideosWrapper videos
{
get { return _videos; }
set { _videos = value; }
}
[XmlAttributeAttribute()]
public string generated_in
{
get { return _generated_in; }
set { _generated_in = value; }
}
[XmlAttributeAttribute()]
public string stat
{
get { return _stat; }
set { _stat = value; }
}
}
[SerializableAttribute]
[XmlTypeAttribute(AnonymousType = true)]
public partial class SearchResponseVideosWrapper
{
private SearchResponseVideosWrapperVideo[] _video;
private string _on_this_page;
private string _page;
private string _perpage;
private string _total;
[XmlElementAttribute("video", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public SearchResponseVideosWrapperVideo[] video
{
get { return _video; }
set { _video = value; }
}
[XmlAttributeAttribute()]
public string on_this_page
{
get { return _on_this_page; }
set { _on_this_page = value; }
}
[XmlAttributeAttribute()]
public string page
{
get { return _page; }
set { _page = value; }
}
[XmlAttributeAttribute()]
public string perpage
{
get { return _perpage; }
set { _perpage = value; }
}
[XmlAttributeAttribute()]
public string total
{
get { return _total; }
set { _total = value; }
}
}
[SerializableAttribute]
[XmlTypeAttribute(AnonymousType = true)]
public partial class SearchResponseVideosWrapperVideo
{
private string _title;
private string _id;
private string _username;
[XmlElement()]
public string title
{
get { return _title; }
set { _title = value; }
}
[XmlAttributeAttribute()]
public string id
{
get { return _id; }
set { _id = value; }
}
[XmlElementAttribute("owner")]
public string username
{
get { return _username; }
set { _username = value; }
}
}
problem is here i think
[XmlElementAttribute("owner")]
public string username
{
get { return _username; }
set { _username = value; }
}
- <owner display_name="Ertan D." id="1387509" is_plus="0" is_pro="0" is_staff="0" profileurl="http://vimeo.com/user1387509" realname="Ertan D." username="user1387509" videosurl="http://vimeo.com/user1387509/videos">
how can I get attribute from owner..
here is exception detail
I get an exception that is There is an error in XML document (1,
1005).
{"Unexpected node type Element. ReadElementString method can only be
called on elements with simple or empty content. Line 1, position
1005."}
System.InvalidOperationException was caught
You need an 'owner' class. You also might consider adding the 'portrait' class with a collection in the 'owner' class.
public class owner
{
[XmlAttributeAttribute]
public string username { get; set; }
}
[SerializableAttribute]
[XmlTypeAttribute(AnonymousType = true)]
public partial class SearchResponseVideosWrapperVideo
{
private string _title;
private string _id;
private string _username;
[XmlElement()]
public string title
{
get { return _title; }
set { _title = value; }
}
[XmlAttributeAttribute()]
public string id
{
get { return _id; }
set { _id = value; }
}
[XmlElementAttribute("owner")]
public owner owner { get; set; }
}
You are annotating username with an XmlElementAttribute for "owner."
That implies that the owner element should be deserialized into the string property username.
If you want to get at username, you first have to deserialize owner into some object.
For example, you could add an Owner class, in the same manner as you created VimeoSearchResponse.
public class Owner
{
private string _owner;
[XmlAttribute]
public string username
{
get { return _owner; }
set { _owner = value; }
}
}

Categories