I need to write GPS-Data in different XMLfiles. The files need to have the following format:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx>
<metadata>
<time>YYYY-MM-DDTHH:MM:SSZ</time>
</metadata>
<trk>
<name>YYYY-MM-DDTHH:MM:SSZ</name>
<trkseg>
<trkpt lat="12.1795" lon="12.3456">
<ele>-46.97</ele>
<time>YYYY-MM-DDTHH:MM:SSZ</time>
</trkpt>
// more trkpt
</trkseg>
</trk>
</gpx>
I tried to do it with an XMLwriter. At first it constructs the part till trkpt.That works. The XmlWriterSettings were included because the Error told me to use ConformanceLevel "Auto" or "fregmented" ,but that didn't solve my issue.
XmlWriterSettings setting = new XmlWriterSettings();
setting.ConformanceLevel = ConformanceLevel.Auto;
setting.Indent = true;
DateTime localDate = DateTime.Now;
xmlWriter[0] = XmlWriter.Create("testbase.xml", setting);
for (int i = 1; i < (numOfXMLWriter); i++)
{
xmlWriter[i] = XmlWriter.Create(test[i].Text, setting);
}
int tmp = 0;
foreach (XmlWriter writer in xmlWriter)
{
writer.WriteStartDocument(true);
writer.WriteStartElement("gpx");
writer.WriteStartElement("metadata");
writer.WriteStartElement("time");
writer.WriteString(localDate.Year + "-" + localDate.Month + "-" + localDate.Day + "T" + localDate.Hour + ":" + localDate.Minute + ":" + localDate.Second);
writer.WriteEndElement(); //time
writer.WriteEndElement(); //metadata
//trk + name
writer.WriteStartElement("trkseg");
}
Later the received GPS-Data is written as individual trkpt.
xmlWriter[id].WriteStartElement("trkpt");
xmlWriter[id].WriteAttributeString("lat", splitData[4]);
xmlWriter[id].WriteAttributeString("lon", splitData[6]);
xmlWriter[id].WriteStartAttribute("ele");
xmlWriter[id].WriteString("0");
xmlWriter[id].WriteEndElement(); //</ele>
xmlWriter[id].WriteStartElement("time");
xmlWriter[id].WriteString(splitData[10][4] + splitData[10][5] + "-" + splitData[10][2] + splitData[10][3] + "-" + splitData[10][0] + splitData[10][1] + "T" + splitData[2][0] + splitData[2][1] + ":" + splitData[2][2] + splitData[2][3] + ":" + splitData[2][4] + splitData[2][5] + "Z");
xmlWriter[id].WriteEndElement(); //</time>
xmlWriter[id].WriteEndElement(); //</trkpt>
The Error says:
InvalidOperationException: "Token StartElement in state EndRootElement would result in an invalid XML document”
I think this is because the XMLwriter Closes all the nodes atomatically and later i try to add another Node on root Level. Is there a possibility to stap the writer from ending the document on it's own?
Thanks for your help!
Jonas
Using xml linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string header = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?><gpx></gpx>";
XDocument doc = XDocument.Parse(header);
XElement gpx = doc.Root;
gpx.Add(new object[] {
new XElement("metadata"), new XElement("time", DateTime.Now.ToString("yyyy-MM-ddthh:mm:ssz")),
new XElement("trk", new object[] {
new XElement("name", DateTime.Now.ToString("yyyy-MM-ddthh:mm:ssz")),
new XElement("trksseg", new object[] {
new XElement("trkpt", new object[] {
new XAttribute("lat", 12.1795),
new XAttribute("lon", 12.3456),
new XElement("ele", -46.97),
new XElement("time",DateTime.Now.ToString("yyyy-MM-ddthh:mm:ssz")),
})
})
})
});
}
}
}
Related
In an xsl-fo file how can I remove some elements
Quickest way, perhaps not the most elegant :
XmlDocument xmlDoc = new XmlDocument();
StringBuilder xmlSb = new StringBuilder();
xmlSb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
xmlSb.AppendLine("<fo:root xmlns:fo=\"http://www.w3.org/1999/XSL/Format\">");
xmlSb.AppendLine(" <fo:layout-master-set>");
xmlSb.AppendLine(" <fo:simple-page-master master-name=\"master\">");
xmlSb.AppendLine(" <fo:region-body margin-bottom=\"0.5in\" margin-top=\"0.9in\" margin-left=\"35pt\"/>");
xmlSb.AppendLine(" <fo:region-before region-name=\"xsl-region-before\" extent=\"0.9in\"/>");
xmlSb.AppendLine(" <fo:region-after region-name=\"xsl-region-after\" extent=\"0.5in\"/>");
xmlSb.AppendLine(" </fo:simple-page-master>");
xmlSb.AppendLine(" </fo:layout-master-set>");
xmlSb.AppendLine(" <fo:page-sequence master-reference=\"master\"/>");
xmlSb.AppendLine("</fo:root>");
// Load xml from string
xmlDoc.LoadXml(xmlSb.ToString());
Console.WriteLine("----- Original xml -----");
Console.WriteLine(xmlSb.ToString());
// Select region-before node
XmlNode regionBeforeNode = xmlDoc.SelectSingleNode("//*[local-name()='region-before']");
// Remove region-before node
regionBeforeNode.ParentNode.RemoveChild(regionBeforeNode);
// Select region-after node
XmlNode regionAfterNode = xmlDoc.SelectSingleNode("//*[local-name()='region-after']");
// Remove region-after node
regionAfterNode.ParentNode.RemoveChild(regionAfterNode);
Console.WriteLine("----- Nodes removed -----");
StringBuilder sbOut = new StringBuilder();
// Pretty indented output
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace
};
using (XmlWriter writer = XmlWriter.Create(sbOut, settings))
{
xmlDoc.Save(writer);
}
Console.WriteLine(sbOut.ToString ());
Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
string xml =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<fo:root xmlns:fo=\"http://www.w3.org/1999/XSL/Format\">" +
" <fo:layout-master-set>" +
" <fo:simple-page-master master-name=\"master\">" +
" <fo:region-body margin-bottom=\"0.5in\" margin-top=\"0.9in\" margin-left=\"35pt\"/>" +
" </fo:simple-page-master>" +
" </fo:layout-master-set>" +
" <fo:page-sequence master-reference=\"master\"/>" +
"</fo:root>";
XDocument doc = XDocument.Parse(xml);
XNamespace nsFo = doc.Root.GetNamespaceOfPrefix("fo");
XElement regionBody = doc.Descendants(nsFo + "region-body").FirstOrDefault();
regionBody.Add(new XElement(nsFo + "test", new object[] { new XAttribute("name", "John")}));
}
}
}
I am still getting warmed up with NetSuite and have come across an issue I can't crack.
I am building a C# function to pull information from an XML soap response from NetSuite. This XML is the result of a saved search call which contains a section that is a join titled customSearchJoin that I am unsure how to access. Below I will show the XML section and my attempts to access it in the C# function.
I am attempting to access the field with the value of 091736418
XML segment:
<platformCore:searchRow xsi:type="tranSales:TransactionSearchRow" xmlns:tranSales="urn:sales_2014_1.transactions.webservices.netsuite.com">
<tranSales:basic xmlns:platformCommon="urn:common_2014_1.platform.webservices.netsuite.com">
<platformCommon:dateCreated>
<platformCore:searchValue>2015-12-17T08:43:00.000-08:00</platformCore:searchValue>
</platformCommon:dateCreated>
<platformCommon:entity>
<platformCore:searchValue internalId="615"/>
</platformCommon:entity>
</tranSales:basic>
<tranSales:customerMainJoin xmlns:platformCommon="urn:common_2014_1.platform.webservices.netsuite.com">
<platformCommon:altName>
<platformCore:searchValue>Some Specific Customer</platformCore:searchValue>
</platformCommon:altName>
</tranSales:customerMainJoin>
<tranSales:itemJoin xmlns:platformCommon="urn:common_2014_1.platform.webservices.netsuite.com">
<platformCommon:itemId>
<platformCore:searchValue>Some Product</platformCore:searchValue>
</platformCommon:itemId>
</tranSales:itemJoin>
<tranSales:customSearchJoin xmlns:platformCommon="urn:common_2014_1.platform.webservices.netsuite.com">
<platformCommon:customizationRef internalId="167" scriptId="custrecord_itmfulfillmentid"/>
<platformCommon:searchRowBasic xsi:type="platformCommon:CustomRecordSearchRowBasic">
<platformCommon:recType internalId="25"/>
<platformCommon:customFieldList>
<platformCore:customField xsi:type="platformCore:SearchColumnStringCustomField" scriptId="custrecord_ssccbarcode" internalId="169">
<platformCore:searchValue>091736418</platformCore:searchValue>
</platformCore:customField>
</platformCommon:customFieldList>
</platformCommon:searchRowBasic>
</tranSales:customSearchJoin>
</platformCore:searchRow>
C# function:
private void testCustomJoinSearch() {
TransactionSearchAdvanced transSearchAdv = new TransactionSearchAdvanced
{
savedSearchScriptId = "customsearch_savedSearchID"
};
SearchResult searchResult = _service.search(transSearchAdv);
if (searchResult.status.isSuccess)
{
Console.WriteLine("Search Success");
foreach (TransactionSearchRow transSearchRow in searchResult.searchRowList)
{
// declare vars
string transInternalID = "";
string ssccBarcode = "";
//normal field
transInternalID = transSearchRow.basic. internalId[0].searchValue.internalId.ToString();
//joined and custom field ? Not sure this loop is correct
foreach (CustomSearchRowBasic customBasicSearchRow in transSearchRow.customSearchJoin)
{
// ????
};
Console.WriteLine("transInternalID {0}", transInternalID);
Console.WriteLine("ssccBarcode {0}", ssccBarcode);
} // end main search row
}
else
{
Console.WriteLine("Search Failure");
Console.WriteLine(searchResult.status.statusDetail);
}
}
Try xml linq. I fixed your xml that was missing some namespace definitions so I added root and then closed the end tags platformCore:searchRow and root.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication70
{
class Program
{
static void Main(string[] args)
{
string xml =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<Root xmlns:platformCore=\"abc\" xmlns:xsi=\"def\">" +
"<platformCore:searchRow xsi:type=\"tranSales:TransactionSearchRow\" xmlns:tranSales=\"urn:sales_2014_1.transactions.webservices.netsuite.com\">" +
"<tranSales:basic xmlns:platformCommon=\"urn:common_2014_1.platform.webservices.netsuite.com\">" +
"<platformCommon:dateCreated>" +
"<platformCore:searchValue>2015-12-17T08:43:00.000-08:00</platformCore:searchValue>" +
"</platformCommon:dateCreated>" +
"<platformCommon:entity>" +
"<platformCore:searchValue internalId=\"615\"/>" +
"</platformCommon:entity>" +
"</tranSales:basic>" +
"<tranSales:customerMainJoin xmlns:platformCommon=\"urn:common_2014_1.platform.webservices.netsuite.com\">" +
"<platformCommon:altName>" +
"<platformCore:searchValue>Some Specific Customer</platformCore:searchValue>" +
"</platformCommon:altName>" +
"</tranSales:customerMainJoin>" +
"<tranSales:itemJoin xmlns:platformCommon=\"urn:common_2014_1.platform.webservices.netsuite.com\">" +
"<platformCommon:itemId>" +
"<platformCore:searchValue>Some Product</platformCore:searchValue>" +
"</platformCommon:itemId>" +
"</tranSales:itemJoin>" +
"<tranSales:customSearchJoin xmlns:platformCommon=\"urn:common_2014_1.platform.webservices.netsuite.com\">" +
"<platformCommon:customizationRef internalId=\"167\" scriptId=\"custrecord_itmfulfillmentid\"/>" +
"<platformCommon:searchRowBasic xsi:type=\"platformCommon:CustomRecordSearchRowBasic\">" +
"<platformCommon:recType internalId=\"25\"/>" +
"<platformCommon:customFieldList>" +
"<platformCore:customField xsi:type=\"platformCore:SearchColumnStringCustomField\" scriptId=\"custrecord_ssccbarcode\" internalId=\"169\">" +
"<platformCore:searchValue>091736418</platformCore:searchValue>" +
"</platformCore:customField>" +
"</platformCommon:customFieldList>" +
"</platformCommon:searchRowBasic>" +
"</tranSales:customSearchJoin>" +
"</platformCore:searchRow>" +
"</Root>";
XDocument doc = XDocument.Parse(xml);
string searchvalue = doc.Descendants().Where(x => x.Name.LocalName == "customSearchJoin")
.Descendants().Where(y => y.Name.LocalName == "searchValue").Select(z => (string)z).FirstOrDefault();
}
}
}
I believe it is something like this:
foreach (CustomSearchRowBasic customBasicSearchRow in transSearchRow.customSearchJoin) {
// ????
CustomRecordSearchRowBasic itmfulfillmentidRecord = customBasicSearchRow.searchRowBasic as CustomRecordSearchRowBasic;
foreach(SearchColumnCustomField customField in itmfulfillmentidRecord.customFieldList) {
if (customField.scriptId == "custrecord_ssccbarcode") {
SearchColumnStringCustomField stringField = customField as SearchColumnStringCustomField;
string itmfulfillmentid = stringField.searchValue;
}
}
}
I need to create a WebService that takes the name of a city as input and returns Location, Country and Weather information of the City. The thing is that the ID, Location, Country is in one XML file and all weather details in another.
<City>
<ID>city1</ID>
<Grid_ref>NG 895608</Grid_ref>
<Name>Berlin</Name>
<Country>Germany</Country>
</City>
<cityWeather>
<ID>city1</ID>
<temperature>20</temperature>
<wind>2</wind>
</cityWeather>
Using c# is it possible to merge everything into 1 file using ID or is there some other way I can do it? I would then search the XML file once, as having 2 different files mixes me up.
You can use DataSet. I suppose you have two XML files. CityWeather.xml et City.xml, you can make this
try
{
XmlTextReader xmlreader1 = new XmlTextReader("C:\\Books1.xml");
XmlTextReader xmlreader2 = new XmlTextReader("C:\\Books2.xml");
DataSet ds = new DataSet();
ds.ReadXml(xmlreader1);
DataSet ds2 = new DataSet();
ds2.ReadXml(xmlreader2);
ds.Merge(ds2);
ds.WriteXml("C:\\Books.xml");
Console.WriteLine("Completed merging XML documents");
}
catch (System.Exception ex)
{
Console.Write(ex.Message);
}
Console.Read();
You can make any changes that meet your need
hope it helps
Use add
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string cityXML =
"<Root>" +
"<City>" +
"<ID>city1</ID>" +
"<Grid_ref>NG 895608</Grid_ref>" +
"<Name>Berlin</Name>" +
"<Country>Germany</Country>" +
"</City>" +
"<City>" +
"<ID>city2</ID>" +
"<Grid_ref>F 5608</Grid_ref>" +
"<Name>Paris</Name>" +
"<Country>France</Country>" +
"</City>" +
"<City>" +
"<ID>city3</ID>" +
"<Grid_ref>RR 608</Grid_ref>" +
"<Name>Rome</Name>" +
"<Country>Italy</Country>" +
"</City>" +
"</Root>";
XElement cities = XElement.Parse(cityXML);
string weatherXML =
"<Root>" +
"<cityWeather>" +
"<ID>city1</ID>" +
"<temperature>20</temperature>" +
"<wind>2</wind>" +
"</cityWeather>" +
"<cityWeather>" +
"<ID>city2</ID>" +
"<temperature>30</temperature>" +
"<wind>3</wind>" +
"</cityWeather>" +
"<cityWeather>" +
"<ID>city3</ID>" +
"<temperature>40</temperature>" +
"<wind>4</wind>" +
"</cityWeather>" +
"</Root>";
XElement weather = XElement.Parse(weatherXML);
List<XElement> cityList = cities.Descendants("City").ToList();
foreach(XElement city in cityList)
{
XElement matchedCity = weather.Descendants("cityWeather").Where(x =>
x.Element("ID").Value == city.Element("ID").Value).FirstOrDefault();
if(matchedCity != null) city.Add(matchedCity);
}
}
}
}
I am trying to create a xml document that need to be serialized against some xml schemas. This is the result now
<?xml version="1.0" encoding="utf-8"?>
<StandardBusinessDocument>
<StandardBusinessDocumentHeader>
<HeaderVersion>1,0</HeaderVersion>
<Sender>
<Identifier>5790000011032</Identifier>
</Sender>
<Receiver>
<Identifier>5790000500000</Identifier>
</Receiver>
<DocumentIdentification>
<Standard>EAN.UCC</Standard>
<TypeVersion>2.8</TypeVersion>
<InstanceIdentifier>DI-35346-34535-xt435345</InstanceIdentifier>
<Type>catalogueItemNotification</Type>
<CreationDateAndTime>2013-12-20T10:46:26+00:00</CreationDateAndTime>
</DocumentIdentification>
</StandardBusinessDocumentHeader>
</StandardBusinessDocument>
And here is what it should look like.
<?xml version="1.0" encoding="utf-8"?>
<sh:StandardBusinessDocument xmlns:sh="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader" xmlns:eanucc="urn:ean.ucc:2" xmlns:gdsn="urn:ean.ucc:gdsn:2" xmlns:align="urn:ean.ucc:align:2" xmlns:chemical_ingredient="urn:ean.ucc:align:chemical_ingredient:2" xmlns:food_beverage_tobacco="urn:ean.ucc:align:food_beverage_tobacco:2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader http://www.gdsregistry.org/2.8/schemas/sbdh/StandardBusinessDocumentHeader.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/CatalogueItemNotificationProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/AttributeValuePairExtensionProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/CaseLevelNonGTINLogisticsUnitExtensionProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/TradeItemExtensionSpecificsProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/ChemicalIngredientExtensionProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/FoodAndBeverageTradeItemExtensionProxy.xsd">
<sh:StandardBusinessDocumentHeader>
<sh:HeaderVersion>1.0</sh:HeaderVersion>
<sh:Sender>
<sh:Identifier Authority="EAN.UCC">5790000011032</sh:Identifier>
</sh:Sender>
<sh:Receiver>
<sh:Identifier Authority="EAN.UCC">5790000500000</sh:Identifier>
</sh:Receiver>
<sh:DocumentIdentification>
<sh:Standard>EAN.UCC</sh:Standard>
<sh:TypeVersion>2.8</sh:TypeVersion>
<sh:InstanceIdentifier>DI-35346-34535-xt435345</sh:InstanceIdentifier>
<sh:Type>catalogueItemNotification</sh:Type>
<sh:CreationDateAndTime>2013-12-20T10:46:26+00:00</sh:CreationDateAndTime>
</sh:DocumentIdentification>
</sh:StandardBusinessDocumentHeader>
</sh:StandardBusinessDocument>
What i have so far in the method where i create the xml is this.
XmlSchemaSet sbdSchema = new XmlSchemaSet();
sbdSchema.Add("http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader", "D:\\Europoultry\\Program\\EPWCF\\EPSystem\\EPSystem\\XMLSchemas\\sdbh\\StandardBusinessDocumentHeader.xsd");
sbdSchema.Add("http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader", "D:\\Europoultry\\Program\\EPWCF\\EPSystem\\EPSystem\\XMLSchemas\\sdbh\\DocumentIdentification.xsd");
sbdSchema.Add("http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader", "D:\\Europoultry\\Program\\EPWCF\\EPSystem\\EPSystem\\XMLSchemas\\sdbh\\BasicTypes.xsd");
sbdSchema.Add("http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader", "D:\\Europoultry\\Program\\EPWCF\\EPSystem\\EPSystem\\XMLSchemas\\sdbh\\BusinessScope.xsd");
sbdSchema.Add("http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader", "D:\\Europoultry\\Program\\EPWCF\\EPSystem\\EPSystem\\XMLSchemas\\sdbh\\Manifest.xsd");
sbdSchema.Add("http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader", "D:\\Europoultry\\Program\\EPWCF\\EPSystem\\EPSystem\\XMLSchemas\\sdbh\\Partner.xsd");
XDocument doc = new XDocument(
new XElement("StandardBusinessDocument",
new XElement("StandardBusinessDocumentHeader",
new XElement("HeaderVersion", "1,0"),
new XElement("Sender",
new XElement("Identifier", "5790000011032")),
new XElement("Receiver",
new XElement("Identifier", "5790000500000")),
new XElement("DocumentIdentification",
new XElement("Standard", "EAN.UCC"),
new XElement("TypeVersion", "2.8"),
new XElement("InstanceIdentifier", "DI-35346-34535-xt435345"),
new XElement("Type", "catalogueItemNotification"),
new XElement("CreationDateAndTime", "2013-12-20T10:46:26+00:00")
)))
);
var savePath = "C:\\GS1TradeSyncItem.xml";
doc.Save(savePath);
I dont think the schemas is being importet right since the element dont have some attibutes on them, but i am not sure if this is what the problem is. Hope one of you can help.
Thanks!
Here is how I would add the namespaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string savePath = #"C:\temp\test.xml";
static void Main(string[] args)
{
string identification =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?> " +
"<sh:StandardBusinessDocument" +
" xmlns:sh=\"http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader\"" +
" xmlns:eanucc=\"urn:ean.ucc:2\" " +
" xmlns:gdsn=\"urn:ean.ucc:gdsn:2\" " +
" xmlns:align=\"urn:ean.ucc:align:2\" " +
" xmlns:chemical_ingredient=\"urn:ean.ucc:align:chemical_ingredient:2\" " +
" xmlns:food_beverage_tobacco=\"urn:ean.ucc:align:food_beverage_tobacco:2\"" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
" xsi:schemaLocation=\"http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader http://www.gdsregistry.org/2.8/schemas/sbdh/StandardBusinessDocumentHeader.xsd" +
" urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/CatalogueItemNotificationProxy.xsd" +
" urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/AttributeValuePairExtensionProxy.xsd" +
" urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/CaseLevelNonGTINLogisticsUnitExtensionProxy.xsd" +
" urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/TradeItemExtensionSpecificsProxy.xsd" +
" urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/ChemicalIngredientExtensionProxy.xsd" +
" urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/FoodAndBeverageTradeItemExtensionProxy.xsd\"" +
"/>";
XDocument doc = XDocument.Parse(identification);
XElement standardBusinessDocument = doc.Root;
XNamespace sh = standardBusinessDocument.Name.Namespace;
standardBusinessDocument.Add(
new XElement(sh + "StandardBusinessDocumentHeader",
new XElement(sh + "HeaderVersion", "1.0"),
new XElement(sh + "Sender",
new XElement(sh + "Identifier", new object[] {new XAttribute("Authority","EAN.UCC"), "5790000011032"})),
new XElement(sh + "Receiver",
new XElement(sh + "Identifier", new object[] {new XAttribute("Authority","EAN.UCC"), "5790000500000"})),
new XElement(sh + "DocumentIdentification",
new XElement(sh + "Standard", "EAN.UCC"),
new XElement(sh + "TypeVersion", "2.8"),
new XElement(sh + "InstanceIdentifier", "DI-35346-34535-xt435345"),
new XElement(sh + "Type", "catalogueItemNotification"),
new XElement(sh + "CreationDateAndTime", "2013-12-20T10:46:26+00:00")
))
);
doc.Save(savePath);
}
}
}
I am trying to generate class by which I can generate a HTML code from an XML file. It does generate the HTML code but when I have more than one tag in my XML file its value is reset.
I hope you could help me.
Here is my code in C#:
public class GenerateHTMLClass
{
public string htmlstringbegin = "<HTML><HEADER><title>My Web-page</title></HEADER><BODY><form>\r\n";
public string htmlstringend = "</form></BODY></HTML>";
public string htmlstring = "";
public GenerateHTMLClass(string xmlfileaddress, string htmlfilenaddress)
{
string id = "";
string name = "";
string type = "";
string value = "";
string htmlstring = "";
XmlTextReader reader = new XmlTextReader(xmlfileaddress);
while (reader.Read())
{
switch (reader.Name)
{
case "GUID":
id = reader.ReadString();
break;
case "Title":
name = reader.ReadString();
break;
case "Type":
type = reader.ReadString();
break;
}
}
htmlstring += "<" + type + " id=" + id + " value=" + name + "/>" + name + "</" + type + ">";
using (FileStream fs = new FileStream(htmlfilenaddress, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8))
{
writer.Write(htmlstringbegin + htmlstring + htmlstringend);
}
}
}
}
My xml file:
<Groups>
<Group1>
<Item1>
<Type>Button</Type>
<GUID>124342345</GUID>
<Title>Name</Title>
</Item1>
</Group1>
<Group2>
<Item2>
<Type>textarea</Type>
<GUID>1243dsfs42345</GUID>
<Title>Name</Title>
</Item2>
</Group2>
</Groups>
Try this:
public void GenerateHTMLClass(string xmlfileaddress, string htmlfilenaddress)
{
List<string> id = new List<string>();
List<string> name = new List<string>();
List<string> type = new List<string>();
List<string> value = new List<string>();
string htmlstring = "";
XmlTextReader reader = new XmlTextReader(xmlfileaddress);
while (reader.Read())
{
switch (reader.Name)
{
case "GUID":
id.Add(reader.ReadString());
break;
case "Title":
name.Add(reader.ReadString());
break;
case "Type":
type.Add(reader.ReadString());
break;
}
}
int i=0;
foreach (var item in id)
{
htmlstring += "<" + type[i] + " id=" + item + " value=" + name[i] + "/>" + name[i] + "</" + type[i] + ">";
i++;
}
using (FileStream fs = new FileStream(htmlfilenaddress, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8))
{
writer.Write(htmlstringbegin + htmlstring + htmlstringend);
}
}
}
But better use XElement class
Try putting the HTML addition code
htmlstring += "<" + type + " id=" + id + " value=" + name + "/>" + name + "</" + type + ">";
into the while loop. This way it will append for every tag, rather than just once after reading all tags.
EDIT: It's slightly more complex, sorry. Change your XML like so:
<Groups>
<Group>
<Item>
<Type>Button</Type>
<GUID>124342345</GUID>
<Title>Name</Title>
</Item>
</Group>
<Group>
<Item>
<Type>textarea</Type>
<GUID>1243dsfs42345</GUID>
<Title>Name</Title>
</Item>
</Group>
</Groups>
Then load it, create a new line for each Item tag. I've used the XElement parser rather than XmlTextReader for ease of use.
var reader = XElement.Load(xmlfileaddress);
foreach (var item in reader.Descendants("Item"))
{
var id = item.Element("GUID").Value;
var name = item.Element("Title").Value;
var type = item.Element("Type").Value;
htmlstring += "<" + type + " id=" + id + " value=" + name + "/>" + name + "</" + type + ">";
}
This will get all your <Item> tags, read their 3 properties, and create a new line for them. If you plan on creating large documents this way, it's advisable to replace your string htmlstring; with a StringBuilder, for performance.