Search Results

Search found 171 results on 7 pages for 'xmlelement'.

Page 4/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • JAXB Annotated class - setting of a variable which is not an element

    - by sswdeveloper
    I have a JAXB annotated class say @XmlRootElement(namespace = "http://www.abc.com/customer") Class Customer{ @XmlElement(namespace = "http://www.abc.com/customer") private String Name; @XmlElement(namespace = "http://www.abc.com/customer") private String Address; @XmlTransient private HashSet set = new HashSet(); public String getName(){ return Name; } public void setName(String name){ this.Name = name; set.add("Name"); } public String getAddress(){ return Address; } public void setAddress(String address){ this.Address = address; set.add("Address"); } public void getSet(){ return set; } I have a XML of the form <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Customer xmlns="http://www.abc.com/customer" > <Name>Ralph</Name> <Address>Newton Street</Address> </Customer> I use JAXB unmarshalling to get the object representation of the XML input. The values for Name and Address are set correctly. However the value of set gets lost(since it is @XMLTransient it gets ignored) Is there any way of ensuring that it is still set in the object which has been unmarshalled? Some other annotation which I can use?

    Read the article

  • JAXB code generation: how to remove a zero occurrence field?

    - by reef
    Hi all, I use JAXB 2.1 to generate Java classes from several XSD files, and I have a problem related to complex type restriction. On of the restrictions modifies the occurence configuration from minOccurs="0" maxOccurs="unbounded" to minOccurs="0" maxOccurs="0". Thus this field is not needed anymore in the restricted type. But actually JAXB generates the restricted class with a [0..1] cardinality instead of 0. By the way the generation is tuned with <xjc:treatRestrictionLikeNewType / so that a XSD restriction is not mapped to a Java class inheritance. Here is an example: Here is the way a field is defined in a complex type A: <element name="qualifier" type="CR" maxOccurs="unbounded" minOccurs="0"/ Here is the way the same field is restricted in another complex type B that restricts A: <element name="qualifier" type="CR" minOccurs="0" maxOccurs="0"/ In the A generated class I have: @XmlElement(name = "qualifier") protected List<CR qualifiers; And in the B generated class I have: protected CR qualifiers; With my poor understanding of JAXB the absence of the XmlElement annotation tells JAXB not to marshall/unmarshall this field. Am I wrong? If I am right is there a way to tell JAXB not to generate the qualifiers field at all? This would be in my opinion a much better generation as it respects the constraints. Any idea, thougths on the topic? Thanks!!

    Read the article

  • Oracle 10.1 and 11.2 produce different XML using the same statement

    - by MindFyer
    I am migrating a database from Oracle 10.1 to 11.2 and I have the following problem. The statement SELECT '<?xml version="1.0" encoding="utf-8" ?>' || (Xml).getClobVal() AS XmlClob FROM ( SELECT XmlElement( "Element1", ( SELECT XmlAgg(tpx.Xml) FROM ( SELECT XmlElement("Element3",XmlForest('content' as Element4)) AS Xml FROM dual ) tpx ) AS "Element2" ) AS Xml FROM dual ) On the original 10.1 database produces XML like this... <?xml version="1.0" encoding="utf-8"?> <Element1> <Element2> <Element3> <ELEMENT4>content</ELEMENT4> </Element3> </Element2> </Element1> On the new 11.2 system it looks like this... <?xml version="1.0" encoding="utf-8"?> <Element1> <Element3> <ELEMENT4>content</ELEMENT4> </Element3> </Element1> Is there some environmental variable I am missing that tells Oracle how to format its XML. There are hundreds of thousands of lines of PL/SQL in the database; it would be a mammoth task to rewrite if it turned out they had changed they way Oracle formats XML between versions. Hopefully someone has come accross this before. Thanks

    Read the article

  • Encrypting XML Element

    - by Kanta
    I have created XML file called users.xml Looks like this: <Users> <user> <uin>"0012345"</uin> <name>black</name> <email>"[email protected]"</email> <created>"3/02/2010"</created> </user> <user> <uin>"123456780"</uin> <name>sam</name> <email>"[email protected]"</email> <created>"3/02/2010"</created> </user> <user> <uin>"123456799"</uin> <name>kblack</name> <email>"[email protected]"</email> <created>"3/02/2010"</created> </user> </Users> I want to encrypt the element. Using code like XmlElement uinelement = (XmlElement)xmldoc.SelectSingleNode("Users/user/uin"); ...encrypts only first UIN from the user.xml file. How can I Encrypt all UIN elements? Thank you Kanta

    Read the article

  • How to Search and Navigate XML Nodes

    - by edison681
    I have the following XML : <LOCALCELL_V18 ID = "0x2d100000"> <MXPWR ID = "0x3d1003a0">100</MXPWR> </LOCALCELL_V18> <LOCALCELL_V18 ID = "0x2d140000"> <MXPWR ID = "0x3d1403a0">200</MXPWR> </LOCALCELL_V18> <LOCALCELL_V18 ID = "0x2d180000"> <MXPWR ID = "0x3d1803a0">300</MXPWR> </LOCALCELL_V18> I want to get the inner text of each <MXPWR>. however, it is not allowed to use ID# to locate the inner text since it is not always the same. here is my code: XmlNodeList LocalCell = xmlDocument.GetElementsByTagName("LOCALCELL_V18"); foreach (XmlNode LocalCell_Children in LocalCell) { XmlElement MXPWR = (XmlElement)LocalCell_Children; XmlNodeList MXPWR_List = MXPWR.GetElementsByTagName("MXPWR"); for (int i = 0; i < MXPWR_List.Count; i++) { MaxPwr_form_str = MXPWR_List[i].InnerText; } } Any opinion will be appreciated.

    Read the article

  • need an empty XML while unmarshalling a JAXB annotated class

    - by sswdeveloper
    I have a JAXB annotated class Customer as follows @XmlRootElement(namespace = "http://www.abc.com/customer") public class Customer{ private String name; private Address address; @XmlTransient private HashSet set = new HashSet<String>(); public String getName(){ return name; } @XmlElement(name = "Name", namespace = "http://www.abc.com/customer" ) public void setName(String name){ this.name = name; set.add("name"); } public String getAddress(){ return address; } @XmlElement(name = "Address", namespace = "http://www.abc.com/customer") public void setAddress(Address address){ this.address = address; set.add("address"); } public HashSet getSet(){ return set; } } I need to return an empty XML representing this to the user, so that he may fill the necesary values in the XML and send a request So what I require is : <Customer> <Name></Name> <Address></Address> </Customer> If i simply create an empty object Customer cust = new Customer() ; marshaller.marshall(cust,sw); all I get is the toplevel element since the other fields of the class are unset. What can I do to get such an empty XML? I tried adding the nillable=true annotation to the elements however, this returns me an XML with the xsi:nil="true" which then causes my unmarshaller to ignore this. How do I achieve this?

    Read the article

  • Spring.net customer namespace parser

    - by ListenToRick
    I have a customer parser which looks like this: [NamespaceParser( Namespace = "http://mysite/schema/cache", SchemaLocationAssemblyHint = typeof(CacheNamespaceParser ), SchemaLocation = "/cache.xsd" ) ] public class CacheNamespaceParser : NamespaceParserSupport { public override void Init() { RegisterObjectDefinitionParser("cache", new CacheParser ()); } } public class CacheParser : AbstractSimpleObjectDefinitionParser { protected override Type GetObjectType(XmlElement element) { return typeof(CacheDefinition); } protected override void DoParse(XmlElement element, ObjectDefinitionBuilder builder) { } protected override bool ShouldGenerateIdAsFallback { get { return true; } } } in the web config i have the following configuration.... <spring> <parsers> <parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data"/> <parser type="App.Web.CacheNamespaceParser, WebApp" /> </parsers> When I run the project I get the following error: An error occurred creating the configuration section handler for spring/parsers: Invalid resource name. Name has to be in 'assembly:<assemblyName>/<namespace>/<resourceName>' format. I put a break point in the CacheNamespaceParser init method and it is called. If I remove from the web config all is well! Any ideas whats wrong

    Read the article

  • How do I deserialize a namespaced element to an object in .net?

    - by pc1oad1etter
    Given this XML snippet: ... <InSide:setHierarchyUpdates> <automaticUpdateInterval>5</automaticUpdateInterval> <shouldRunAutomaticUpdates>true<shouldRunAutomaticUpdates> </InSide:setHierarchyUpdates> ... I am attempting to serialize this object: Imports System.Xml.Serialization <XmlRoot(ElementName:="setHierarchyUpdates", namespace:="InSide")> _ Public Class HierarchyUpdate <XmlElement(ElementName:="shouldRunAutomaticUpdates")> _ Public shouldRunAutomaticUpdates As Boolean <XmlElement(ElementName:="automaticUpdateInterval")> _ Public automaticUpdateInterval As Integer End Class Like this: Dim hierarchyUpdater As New HierarchyUpdate Dim x As New XmlSerializer(hierarchyUpdater.GetType) Dim objReader As Xml.XmlNodeReader = New Xml.XmlNodeReader(myXMLNode) hierarchyUpdater = x.Deserialize(objReader) However, the object, after deserialization, has values of false and zero. If I switch the objReader to a streamreader and read this in as a file, with none of its parents and no namespaces, it works: <setHierarchyUpdates> <automaticUpdateInterval>5</automaticUpdateInterval> <shouldRunAutomaticUpdates>true<shouldRunAutomaticUpdates> </setHierarchyUpdates> What am I doing wrong? Should I use something other than XMLRoot in the class definition, because, as an XML node, it's not really the root? If so, what? Why are no errors returned when this fails?

    Read the article

  • How can I test a parser for a bespoke XML schema?

    - by Greg B
    I'm parsing a bespoke XML format into an object graph using .NET 4.0. My parser is using the System.XML namespace internally, I'm then interrogating the relevant properties of XmlNodes to create my object graph. I've got a first cut of the parser working on a basic input file and I want to put some unit tests around this before I progress on to more complex input files. Is there a pattern for how to test a parser such as this? When I started looking at this, my first move was to new up and XmlDocument, XmlNamespaceManager and create an XmlElement. But it occurs to me that this is quite lengthy and prone to human error. My parser is quite recursive as you can imagine and this might lead to testing the full system rather than the individual units (methods) of the system. So a second question might be What refactoring might make a recursive parser more testable?

    Read the article

  • Using JAXB to unmarshal/marshal a List<String> - Inheritance

    - by gerry
    I've build the following case. An interface for all JAXBLists: public interface JaxbList<T> { public abstract List<T> getList(); } And an base implementation: @XmlRootElement(name="list") public class JaxbBaseList<T> implements JaxbList<T>{ protected List<T> list; public JaxbBaseList(){} public JaxbBaseList(List<T> list){ this.list=list; } @XmlElement(name="item" ) public List<T> getList(){ return list; } } As well as an implementation for a list of URIs: @XmlRootElement(name="uris") public class JaxbUriList2 extends JaxbBaseList<String> { public JaxbUriList2() { super(); } public JaxbUriList2(List<String> list){ super(list); } @Override @XmlElement(name="uri") public List<String> getList() { return list; } } And I'm using the List in the following way: public JaxbList<String> init(@QueryParam("amount") int amount){ List<String> entityList = new Vector<String>(); ... enityList.add("http://uri"); ... return new JaxbUriList2(entityList); } I thought the output should be: <uris> <uri> http://uri </uri> ... </uris> But it is something like this: <uris> <item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string"> http://uri </item> ... <uri> http://uri </uri> ... </uris> I think it has something to do with the inheritance, but I don't get it... What's the problem? - How can I fix it? Thanks in advance!

    Read the article

  • MVVM Light Toolkit throws an System.IO.FileLoadException

    - by joebeazelman
    I'm running VS 2010 along with Expression Blend 4 beta. I created a MVVM Light project from the supplied templates and I get a System.IO.FileLoadException when I try to view the MainWindow.Xaml in VS 2010 designer window. The template already references System.Windows.Interactivity. Here are the details of the exception: System.IO.FileLoadException Could not load file or assembly 'System.Windows.Interactivity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515) at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.Assembly.Load(AssemblyName assemblyRef) at MS.Internal.Package.VSIsolationProviderService.RemoteReferenceProxy.VsReflectionResolver.GetRuntimeAssembly(Assembly reflectionAssembly) at Microsoft.Windows.Design.Metadata.ReflectionMetadataContext.CachingReflectionResolver.GetRuntimeAssembly(Assembly reflectionAssembly) at Microsoft.Windows.Design.Metadata.ReflectionMetadataContext.Microsoft.Windows.Design.Metadata.IReflectionResolver.GetRuntimeAssembly(Assembly reflectionAssembly) at MS.Internal.Metadata.ClrAssembly.GetRuntimeMetadata(Object reflectionMetadata) at Microsoft.Windows.Design.Metadata.AttributeTableContainer.d_c.MoveNext() at Microsoft.Windows.Design.Metadata.AttributeTableContainer.GetAttributes(Assembly assembly, Type attributeType, Func`2 reflectionMapper) at MS.Internal.Metadata.ClrAssembly.GetAttributes(ITypeMetadata attributeType) at MS.Internal.Design.Metadata.Xaml.XamlAssembly.get_XmlNamespaceCompatibilityMappings() at Microsoft.Windows.Design.Metadata.Xaml.XamlExtensionImplementations.GetXmlNamespaceCompatibilityMappings(IAssemblyMetadata sourceAssembly) at Microsoft.Windows.Design.Metadata.Xaml.XamlExtensions.GetXmlNamespaceCompatibilityMappings(IAssemblyMetadata source) at MS.Internal.Design.Metadata.ReflectionProjectNode.BuildSubsumption() at MS.Internal.Design.Metadata.ReflectionProjectNode.SubsumingNamespace(Identifier identifier) at MS.Internal.Design.Markup.XmlElement.BuildScope(PrefixScope parentScope, IParseContext context) at MS.Internal.Design.Markup.XmlElement.ConvertToXaml(XamlElement parent, PrefixScope parentScope, IParseContext context, IMarkupSourceProvider provider) at MS.Internal.Design.DocumentModel.DocumentTrees.Markup.XamlSourceDocument.FullParse(Boolean convertToXamlWithErrors) at MS.Internal.Design.DocumentModel.DocumentTrees.Markup.XamlSourceDocument.get_RootItem() at Microsoft.Windows.Design.DocumentModel.Trees.ModifiableDocumentTree.get_ModifiableRootItem() at Microsoft.Windows.Design.DocumentModel.MarkupDocumentManagerBase.get_LoadState() at MS.Internal.Host.PersistenceSubsystem.Load() at MS.Internal.Host.Designer.Load() at MS.Internal.Designer.VSDesigner.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedView.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedDesignerFactory.Load(IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.Load() at MS.Internal.Designer.DesignerPane.LoadDesignerView() System.NotSupportedException An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.

    Read the article

  • Please help me understand why my XSL Transform is not transforming

    - by Damovisa
    I'm trying to transform one XML format to another using XSL. Try as I might, I can't seem to get a result. I've hacked away at this for a while now and I've had no success. I'm not even getting any exceptions. I'm going to post the entire code and hopefully someone can help me work out what I've done wrong. I'm aware there are likely to be problems in the xsl I have in terms of selects and matches, but I'm not fussed about that at the moment. The output I'm getting is the input XML without any XML tags. The transformation is simply not occurring. Here's my XML Document: <?xml version="1.0"?> <Transactions> <Account> <PersonalAccount> <AccountNumber>066645621</AccountNumber> <AccountName>A Smith</AccountName> <CurrentBalance>-200125.96</CurrentBalance> <AvailableBalance>0</AvailableBalance> <AccountType>LOAN</AccountType> </PersonalAccount> </Account> <StartDate>2010-03-01T00:00:00</StartDate> <EndDate>2010-03-23T00:00:00</EndDate> <Items> <Transaction> <ErrorNumber>-1</ErrorNumber> <Amount>12000</Amount> <Reference>Transaction 1</Reference> <CreatedDate>0001-01-01T00:00:00</CreatedDate> <EffectiveDate>2010-03-15T00:00:00</EffectiveDate> <IsCredit>true</IsCredit> <Balance>-324000</Balance> </Transaction> <Transaction> <ErrorNumber>-1</ErrorNumber> <Amount>11000</Amount> <Reference>Transaction 2</Reference> <CreatedDate>0001-01-01T00:00:00</CreatedDate> <EffectiveDate>2010-03-14T00:00:00</EffectiveDate> <IsCredit>true</IsCredit> <Balance>-324000</Balance> </Transaction> </Items> </Transactions> Here's my XSLT: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" /> <xsl:param name="currentdate"></xsl:param> <xsl:template match="Transactions"> <xsl:element name="OFX"> <xsl:element name="SIGNONMSGSRSV1"> <xsl:element name="SONRS"> <xsl:element name="STATUS"> <xsl:element name="CODE">0</xsl:element> <xsl:element name="SEVERITY">INFO</xsl:element> </xsl:element> <xsl:element name="DTSERVER"><xsl:value-of select="$currentdate" /></xsl:element> <xsl:element name="LANGUAGE">ENG</xsl:element> </xsl:element> </xsl:element> <xsl:element name="BANKMSGSRSV1"> <xsl:element name="STMTTRNRS"> <xsl:element name="TRNUID">1</xsl:element> <xsl:element name="STATUS"> <xsl:element name="CODE">0</xsl:element> <xsl:element name="SEVERITY">INFO</xsl:element> </xsl:element> <xsl:element name="STMTRS"> <xsl:element name="CURDEF">AUD</xsl:element> <xsl:element name="BANKACCTFROM"> <xsl:element name="BANKID">RAMS</xsl:element> <xsl:element name="ACCTID"><xsl:value-of select="Account/PersonalAccount/AccountNumber" /></xsl:element> <xsl:element name="ACCTTYPE"><xsl:value-of select="Account/PersonalAccount/AccountType" /></xsl:element> </xsl:element> <xsl:element name="BANKTRANLIST"> <xsl:element name="DTSTART"><xsl:value-of select="StartDate" /></xsl:element> <xsl:element name="DTEND"><xsl:value-of select="EndDate" /></xsl:element> <xsl:for-each select="Items/Transaction"> <xsl:element name="STMTTRN"> <xsl:element name="TRNTYPE"><xsl:choose><xsl:when test="IsCredit">CREDIT</xsl:when><xsl:otherwise>DEBIT</xsl:otherwise></xsl:choose></xsl:element> <xsl:element name="DTPOSTED"><xsl:value-of select="EffectiveDate" /></xsl:element> <xsl:element name="DTUSER"><xsl:value-of select="CreatedDate" /></xsl:element> <xsl:element name="TRNAMT"><xsl:value-of select="Amount" /></xsl:element> <xsl:element name="FITID" /> <xsl:element name="NAME"><xsl:value-of select="Reference" /></xsl:element> <xsl:element name="MEMO"><xsl:value-of select="Reference" /></xsl:element> </xsl:element> </xsl:for-each> </xsl:element> <xsl:element name="LEDGERBAL"> <xsl:element name="BALAMT"><xsl:value-of select="Account/PersonalAccount/CurrentBalance" /></xsl:element> <xsl:element name="DTASOF"><xsl:value-of select="EndDate" /></xsl:element> </xsl:element> </xsl:element> </xsl:element> </xsl:element> </xsl:element> </xsl:template> </xsl:stylesheet> Here's my method to transform my XML: public string TransformToXml(XmlElement xmlElement, Dictionary<string, object> parameters) { string strReturn = ""; // Load the XSLT Document XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(xsltFileName); // arguments XsltArgumentList args = new XsltArgumentList(); if (parameters != null && parameters.Count > 0) { foreach (string key in parameters.Keys) { args.AddParam(key, "", parameters[key]); } } //Create a memory stream to write to Stream objStream = new MemoryStream(); // Apply the transform xslt.Transform(xmlElement, args, objStream); objStream.Seek(0, SeekOrigin.Begin); // Read the contents of the stream StreamReader objSR = new StreamReader(objStream); strReturn = objSR.ReadToEnd(); return strReturn; } The contents of strReturn is an XML tag (<?xml version="1.0" encoding="utf-8"?>) followed by a raw dump of the contents of the original XML document, stripped of XML tags. What am I doing wrong here?

    Read the article

  • Handling FormatExceptions using XmlSerializer.Deserialize

    - by qntmfred
    I have a third party web service that returns this xml <book> <release_date>0000-00-00</release_date> </book> I am trying to deserialize it into this class public class Book { [XmlElement("release_date")] public DateTime ReleaseDate { get; set; } } But because 0000-00-00 isn't a valid DateTime, I get a FormatException. What's the best way to handle this?

    Read the article

  • Unable to cast lists with Reflection in C#

    - by DrLazer
    I am having a lot of trouble with Reflection in C# at the moment. The app I am writing allows the user to modify the attributes of certain objects using a config file. I want to be able to save the object model (users project) to XML. The function below is called in the middle of a foreach loop, looping through a list of objects that contain all the other objects in the project within them. The idea is, that it works recursively to translate the object model into XML. Dont worry about the call to "Unreal" that just modifes the name of the objects slightly if they contain certain words. private void ReflectToXML(object anObject, XmlElement parentElement) { Type aType = anObject.GetType(); XmlElement anXmlElement = m_xml.CreateElement(Unreal(aType.Name)); parentElement.AppendChild(anXmlElement); PropertyInfo[] pinfos = aType.GetProperties(); //loop through this objects public attributes foreach (PropertyInfo aInfo in pinfos) { //if the attribute is a list Type propertyType = aInfo.PropertyType; if ((propertyType.IsGenericType)&&(propertyType.GetGenericTypeDefinition() == typeof(List<>))) { List<object> listObjects = (aInfo.GetValue(anObject,null) as List<object>); foreach (object aListObject in listObjects) { ReflectToXML(aListObject, anXmlElement); } } //attribute is not a list else anXmlElement.SetAttribute(aInfo.Name, ""); } } If an object attributes are just strings then it should be writing them out as string attributes in the XML. If an objects attributes are lists, then it should recursively call "ReflectToXML" passing itself in as a parameter, thereby creating the nested structure I require that nicely reflect the object model in memory. The problem I have is with the line List<object> listObjects = (aInfo.GetValue(anObject,null) as List<object>); The cast doesn't work and it just returns null. While debugging I changed the line to object temp = aInfo.GetValue(anObject,null); slapped a breakpoint on it to see what "GetValue" was returning. It returns a "Generic list of objects" Surely I should be able to cast that? The annoying thing is that temp becomes a generic list of objects but because i declared temp as a singular object, I can't loop through it because it has no Enumerator. How can I loop through a list of objects when I only have it as a propertyInfo of a class? I know at this point I will only be saving a list of empty strings out anyway, but thats fine. I would be happy to see the structure save out for now. Thanks in advance

    Read the article

  • Java object to XML Elements?

    - by DaveKub
    I'm working on a webservices client app and I have it mostly working. I can retrieve and read data from the third-party webservice fine. Now I need to submit some data and I'm stuck. The classes for the objects I'm retrieving/submitting were generated from XSD files via the xjc tool. The part I'm stuck on is turning one of those objects into an XML tree to submit to the webservice. When I retrieve/send a request from/to the ws, it contains a 'payload' object. This is defined in java code as (partial listing): @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PayloadType", propOrder = { "compressed", "document", "any", "format" }) public class PayloadType { @XmlElement(name = "Compressed") protected String compressed; @XmlElement(name = "Document") protected List<String> document; @XmlAnyElement protected List<Element> any; protected String format; public List<Element> getAny() { if (any == null) { any = new ArrayList<Element>(); } return this.any; } } The only field I'm concerned with is the 'any' field which contains an XML tree. When I retrieve data from the ws, I read that field with something like this: ('root' is of org.w3c.dom.Element type and is the result of calling 'getAny().get(0)' on the payload object) NodeList nl = root.getElementsByTagName("ns1:Process"); // "ns1:Process" is an XML node to do something with if (nl != null && nl.getLength() > 0) { for (int i = 0; i < nl.getLength(); i++) { Element proc = (Element) nl.item(i); try { // do something with the 'proc' Element here... } catch (Exception ex) { // handle problems here... } } } Submitting data is where I'm stuck. How do I take a java object created from one of the classes generated from XSD and turn it into an Element object that I can add to the 'any' List of the payload object?? For instance, if I have a DailyData class and I create and populate it with data: DailyData dData = new DailyData(); dData.setID = 34; dData.setValues = "3,5,76,23"; How do I add that 'dData' object to the 'any' List of the payload object? It has to be an Element. Do I do something with a JAXBContext marshaller? I've used that to dump the 'dData' object to the screen to check the XML structure. I'm sure the answer is staring me in the face but I just can't see it! Dave

    Read the article

  • How to specify the order of XmlAttributes, using XmlSerializer

    - by demoncodemonkey
    XmlElement has an "Order" attribute which you can use to specify the precise order of your properties (in relation to each other anyway) when serializing using XmlSerializer. Is there a similar thing for XmlAttribute? I just want to set the order of the attributes from something like <MyType end="bob" start="joe" /> to <MyType start="joe" end="bob" /> This is just for readability, my own benefit really.

    Read the article

  • What are the benefits of using ORM over XML Serialization/Deserialization?

    - by Tequila Jinx
    I've been reading about NHibernate and Microsoft's Entity Framework to perform Object Relational Mapping against my data access layer. I'm interested in the benefits of having an established framework to perform ORM, but I'm curious as to the performance costs of using it against standard XML Serialization and Deserialization. Right now, I develop stored procedures in Oracle and SQL Server that use XML Types for either input or output parameters and return or shred XML depending on need. I use a custom database command object that uses generics to deserialize the XML results into a specified serializable class. By using a combination of generics, xml (de)serialization and Microsoft's DAAB, I've got a process that's fairly simple to develop against regardless of the data source. Moreover, since I exclusively use Stored Procedures to perform database operations, I'm mostly protected from changes in the data structure. Here's an over-simplified example of what I've been doing. static void main() { testXmlClass test = new test(1); test.Name = "Foo"; test.Save(); } // Example Serializable Class ------------------------------------------------ [XmlRootAttribute("test")] class testXmlClass() { [XmlElement(Name="id")] public int ID {set; get;} [XmlElement(Name="name")] public string Name {set; get;} //create an instance of the class loaded with data. public testXmlClass(int id) { GenericDBProvider db = new GenericDBProvider(); this = db.ExecuteSerializable("myGetByIDProcedure"); } //save the class to the database... public Save() { GenericDBProvider db = new GenericDBProvider(); db.AddInParameter("myInputParameter", DbType.XML, this); db.ExecuteSerializableNonQuery("mySaveProcedure"); } } // Database Handler ---------------------------------------------------------- class GenericDBProvider { public T ExecuteSerializable<T>(string commandText) where T : class { XmlSerializer xml = new XmlSerializer(typeof(T)); // connection and command code is assumed for the purposes of this example. // the final results basically just come down to... return xml.Deserialize(commandResults) as T; } public void ExecuteSerializableNonQuery(string commandText) { // once again, connection and command code is assumed... // basically, just execute the command along with the specified // parameters which have been serialized. } public void AddInParameter(string name, DbType type, object value) { StringWriter w = new StringWriter(); XmlSerializer x = new XmlSerializer(value.GetType()); //handle serialization for serializable classes. if (type == DbType.Xml && (value.GetType() != typeof(System.String))) { x.Serialize(w, value); w.Close(); // store serialized object in a DbParameterCollection accessible // to my other methods. } else { //handle all other parameter types } } } I'm starting a new project which will rely heavily on database operations. I'm very curious to know whether my current practices will be sustainable in a high-traffic situation and whether or not I should consider switching to NHibernate or Microsoft's Entity Framework to perform what essentially seems to boil down to the same thing I'm currently doing. I appreciate any advice you may have.

    Read the article

  • Using Xpath With Default Namespace in C#

    - by macleojw
    I've got an XML document with a default namespace. I'm using a XPathNavigator to select a set of nodes using Xpath as follows: XmlElement myXML = ...; XPathNavigator navigator = myXML.CreateNavigator(); XPathNodeIterator result = navigator.Select("/outerelement/innerelement"); I am not getting any results back: I'm assuming this is because I am not specifying the namespace. How can I include the namespace in my select?

    Read the article

  • Blocking problem, C#, .net, Deserializing XML to object problem

    - by fernando
    Hi I have a blocking problem I have XML file under some url http://myserver/mywebApp/myXML.xml In the below code which I run in Console Application, bookcollection has null Books field :( <books> <book id="5352"> <date>1986-05-05</date> <title> Alice in chains </title> </book> <book id="4334"> <date>1986-05-05</date> <title> 1000 ways to heaven </title> </book> <book id="1111"> <date>1986-05-05</date> <title> Kitchen and me </title> </book> </books> XmlDocument doc = new XmlDocument(); doc.Load("http://myserver/mywebapp/myXML.xml"); BookCollection books = new BookCollection(); XmlNodeReader reader2 = new XmlNodeReader(doc.DocumentElement); XmlSerializer ser2 = new XmlSerializer(books.GetType()); object obj = ser2.Deserialize(reader2); BookCollection books2= (BookCollection)obj; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { [Serializable()] public class Book { [System.Xml.Serialization.XmlAttribute("id")] public string id { get; set; } [System.Xml.Serialization.XmlElement("date")] public string date { get; set; } [System.Xml.Serialization.XmlElement("title")] public string title { get; set; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; namespace ConsoleApplication1 { [Serializable()] [System.Xml.Serialization.XmlRootAttribute("books", Namespace = "", IsNullable = false)] public class BookCollection { [XmlArray("books")] [XmlArrayItem("book", typeof(Book))] public Book[] Books { get; set; } } }

    Read the article

  • XmlSerializer: The string '' is not a valid AllXsd value.

    - by ryudice
    I'm getting this message,"The string '7/22/2006 12:00:00 AM' is not a valid AllXsd value.", when deserializing an XML, the element contains a date, this is the property that is supposed to be mapped to the element: [XmlElement("FEC_INICIO_REL",typeof(DateTime))] public DateTime? FechaInicioRelacion { get; set; } Am I doing something wrong?

    Read the article

  • Blocking problem Deserializing XML to object problem

    - by fernando
    I have a blocking problem I have XML file under some url http://myserver/mywebApp/myXML.xml In the below code which I run in Console Application, bookcollection has null Books field :( <books> <book id="5352"> <date>1986-05-05</date> <title> Alice in chains </title> </book> <book id="4334"> <date>1986-05-05</date> <title> 1000 ways to heaven </title> </book> <book id="1111"> <date>1986-05-05</date> <title> Kitchen and me </title> </book> </books> XmlDocument doc = new XmlDocument(); doc.Load("http://myserver/mywebapp/myXML.xml"); BookCollection books = new BookCollection(); XmlNodeReader reader2 = new XmlNodeReader(doc.DocumentElement); XmlSerializer ser2 = new XmlSerializer(books.GetType()); object obj = ser2.Deserialize(reader2); BookCollection books2= (BookCollection)obj; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { [Serializable()] public class Book { [System.Xml.Serialization.XmlAttribute("id")] public string id { get; set; } [System.Xml.Serialization.XmlElement("date")] public string date { get; set; } [System.Xml.Serialization.XmlElement("title")] public string title { get; set; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; namespace ConsoleApplication1 { [Serializable()] [System.Xml.Serialization.XmlRootAttribute("books", Namespace = "", IsNullable = false)] public class BookCollection { [XmlArray("books")] [XmlArrayItem("book", typeof(Book))] public Book[] Books { get; set; } } }

    Read the article

  • xmlns='' was not expected when deserializing nested classes

    - by Mavrik
    I have a problem when attempting to serialize class on a server, send it to the client and deserialize is on the destination. On the server I have the following two classes: [XmlRoot("StatusUpdate")] public class GameStatusUpdate { public GameStatusUpdate() {} public GameStatusUpdate(Player[] players, Command command) { this.Players = players; this.Update = command; } [XmlArray("Players")] public Player[] Players { get; set; } [XmlElement("Command")] public Command Update { get; set; } } and [XmlRoot("Player")] public class Player { public Player() {} public Player(PlayerColors color) { Color = color; ... } [XmlAttribute("Color")] public PlayerColors Color { get; set; } [XmlAttribute("X")] public int X { get; set; } [XmlAttribute("Y")] public int Y { get; set; } } (The missing types are all enums). This generates the following XML on serialization: <?xml version="1.0" encoding="utf-16"?> <StatusUpdate> <Players> <Player Color="Cyan" X="67" Y="32" /> </Players> <Command>StartGame</Command> </StatusUpdate> On the client side, I'm attempting to deserialize that into following classes: [XmlRoot("StatusUpdate")] public class StatusUpdate { public StatusUpdate() { } [XmlArray("Players")] [XmlArrayItem("Player")] public PlayerInfo[] Players { get; set; } [XmlElement("Command")] public Command Update { get; set; } } and [XmlRoot("Player")] public class PlayerInfo { public PlayerInfo() { } [XmlAttribute("X")] public int X { get; set; } [XmlAttribute("Y")] public int Y { get; set; } [XmlAttribute("Color")] public PlayerColor Color { get; set; } } However, the deserializer throws an exception: There is an error in XML document (2, 2). <StatusUpdate xmlns=''> was not expected. What am I missing or doing wrong?

    Read the article

  • JAXB doesn't unmarshal list of interfaces

    - by Joker_vD
    It seems JAXB can't read what it writes. Consider the following code: interface IFoo { void jump(); } @XmlRootElement class Bar implements IFoo { @XmlElement public String y; public Bar() { y = ""; } public Bar(String y) { this.y = y; } @Override public void jump() { System.out.println(y); } } @XmlRootElement class Baz implements IFoo { @XmlElement public int x; public Baz() { x = 0; } public Baz(int x) { this.x = x; } @Override public void jump() { System.out.println(x); } } @XmlRootElement public class Holder { private List<IFoo> things; public Holder() { things = new ArrayList<>(); } @XmlElementWrapper @XmlAnyElement public List<IFoo> getThings() { return things; } public void addThing(IFoo thing) { things.add(thing); } } // ... try { JAXBContext context = JAXBContext.newInstance(Holder.class, Bar.class, Baz.class); Holder holder = new Holder(); holder.addThing(new Bar("1")); holder.addThing(new Baz(2)); holder.addThing(new Baz(3)); for (IFoo thing : holder.getThings()) { thing.jump(); } StringWriter s = new StringWriter(); context.createMarshaller().marshal(holder, s); String data = s.toString(); System.out.println(data); StringReader t = new StringReader(data); Holder holder2 = (Holder)context.createUnmarshaller().unmarshal(t); for (IFoo thing : holder2.getThings()) { thing.jump(); } } catch (Exception e) { System.err.println(e.getMessage()); } It's a simplified example, of course. The point is that I have to store two very differently implemented classes, Bar and Baz, in one collection. Well, I observed that they have pretty similar public interface, so I created an interface IFoo and made them two to implement it. Now, I want to have tools to save and load this collection to/from XML. Unfortunately, this code doesn't quite work: the collection is saved, but then it cannot be loaded! The intended output is 1 2 3 some xml 1 2 3 But unfortunately, the actual output is 1 2 3 some xml com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to testapplication1.IFoo Apparently, I need to use the annotations in a different way? Or to give up on JAXB and look for something else? I, well, can write "XMLNode toXML()" method for all classes I wan't to (de)marshal, but...

    Read the article

  • C# xml Class to substitute ini files

    - by Eduardo
    Hi guys, I am learning Windows Forms in C#.NET 2008 and i want to build a class to work with SIMPLE xml files (config file like INI files), but i just need a simple class (open, getvalue, setvalue, creategroup, save and close functions), to substitute of ini files. I already did something and it is working but I am having trouble when I need to create different groups, something like this: <?xml version="1.0" encoding="utf-8"?> <CONFIG> <General> <Field1>192.168.0.2</Field1> </General> <Data> <Field1>Joseph</Field1> <Field2>Locked</Field2> </Data> </CONFIG> how can i specify that i want to read the field1 of [data] group? note that i have same field name in both groups (Field1)! I am using System.Linq, something like this: To open document: XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(FilePath); To save document: xmlDoc.Save(FilePath); To get value: public string getValue(string Field) { string result = ""; try { XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field); if (xmlComum.Item(0) == null) result = ""; else result = xmlComum.Item(0).InnerText; } catch (Exception ex) { return ""; } return result; } To set value: public void setValue(string Group, string Field, string FieldValue) { try { XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field); if (xmlComum.Item(0) == null) { xmlComum = xmlDoc.GetElementsByTagName(Group); if (xmlComum.Item(0) == null) { // create group createGroup(Group); xmlComum = xmlDoc.GetElementsByTagName(Group); } XmlElement xmlE = xmlDoc.CreateElement(Field); XmlText xmlT = xmlDoc.CreateTextNode(FieldValue); xmlE.AppendChild(xmlT); xmlComum.Item(0).AppendChild(xmlE); } else { // item already exists, just change its value xmlComum.Item(0).InnerText = Value; } xmlDoc.Save(FilePath); } catch (Exception ex) { } } The CreateGroup code: public void createGroup(string Group) { try { XmlElement xmlComum = xmlDoc.CreateElement(Group); xmlDoc.DocumentElement.AppendChild(xmlComum); xmlDoc.Save(FilePath); } catch (Exception ex) { } } Thank You!

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >