I've been trying to read an xml file from an external source to get it into a dataset. I've taken the schema and compiled my class through xsd and have loaded it into the solution.
my xml:
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<CAMDealerManifest AssetURL="http://www.the placewherethefilelives.com/CAMPublic/d98c8185/" DealerCode="41065" DealerGuid="bc0d0bc8-b37b-11e3-a345-ac162dbc18f8" DealerName="Ron Hibbard Toyota" ManifestId="13" ManifestURL="http://www.toyota.com/CAMPublic/d/41065-bc0d0bc8.xml" Path="41065-bc0d0bc8" ProviderId="1011" WebsiteVendorName="WorldDealer">
<CAMCampaigns count="15" dateTime="2014-09-16T17:18:40.877-07:00">
<CAMCampaign ManifestId="13" endDate="2014-12-31T11:59:59-08:00" flightDates="08/01/14 - 12/31/14" geography="National" groupName="National" id="68" name="National - Corolla Style Elevated" priority="0" required="false" startDate="2014-08-01T12:00:00-07:00">
<CAMCreative SubGroup="Corolla Style Elevated" Id="49" Name="National - Corolla Style Elevated" ImageAltText="Toyota's national banner for the stylish 2014 Corolla" ImageSearchTerms="Toyota, 2014 Corolla, Style Elevated, New Heights" Link="New Inventory" Model="Corolla" MonthYear="08-2014" Priority="3" Required="false">
<CAMCreativeSource CAMAssetCount="1" Height="409" Width="990" MediaBinAssetId="0E1C886A-C5CE-4409-AD36-7070D614A7A6" MediaBinFileName="03-14_01_2014_nat-style-elevated_990x409_0000000460_corolla_o_xta.jpg">
<CAMAsset Path="National/Corolla-Style-Elevated/National---Corolla-Style-Elevated/990/409/" Id="1273" Name="08-14_01_National-Corolla-Style-Elevated_990x409_431_Corolla_O_xta.jpg" Height="409" Width="990" assetType="JPG" Guid="b9f4d3cd-fefd-4ff3-b209-338f409e551c" Md5Hex="3e328dc32a2db9fc1f3d6a2167d3e5d2">
<CAMTracking>
<SiteCatalyst version="1.0">
<Click tmsomni.events="event28" tmsomni.products=";08-14_01_National-Corolla-Style-Elevated_990x409_431_Corolla_O_xta;;;event28=1"/>
<Impression tmsomni.events="event29" tmsomni.products=";08-14_01_National-Corolla-Style-Elevated_990x409_431_Corolla_O_xta;;event29=1;evar43=img|evar61=corolla|evar54=o|evar49={$CAM_PAGE_POSITION}"/>
</SiteCatalyst>
</CAMTracking>
</CAMAsset>
</CAMCreativeSource>
</CAMCreative>
</CAMCampaign>
</CAMCampaigns>
<CAMExpiredCampaigns count="0" dateTime="2014-09-16T17:18:40.873-07:00"/>
</CAMDealerManifest>
I can't seem to get this xml to list or put into a dataset. I'm new to deserializing xml and could use some assistance.
Simply call ReadXml with the path to the file:
var dataSet = new DataSet();
dataSet.ReadXml(string PathToFile);
Works pretty well; will even create all the relations (notice CAMDealerManifestId in the screenshot).
Your file went in with only a modification to the XML declaration -- had to change standalone value from true to yes:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
If you're reading this in as a string, you could do something like this:
var xmlString = HoweverYouGetTheString().Split(new string[] { "\r\n" }, StringSplitOptions.None);
xmlString[0] = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
using (var reader = new System.IO.StringReader(String.Join("\r\n", xmlString)))
{
dataSet.ReadXml(reader);
}
Related
A portion of my c# .NET program contains code to modify elements within an XML document. The code works fine in terms of modifying the values based on the variables I'm setting elsewhere in the code, but the problem is that whitespace is being added to all of the the elements when the xml file is saved with the updates.
I am not accessing this element at all in my code. I am assuming that it's because of the quotation marks for the algorithm namespace value, because I can't see any other reason why this would happen. I am using Preserve Namespace on load, and Disable Formatting on save.
So question is, why is it adding this extra whitespace, and how can I stop it?
XML (Source File)
<?xml version="1.0" encoding="UTF-8"?>
<PackingList xmlns="http://www.smpte-ra.org/schemas/2067-2/2016/PKL">
<Id>urn:uuid:296a656c-3610-4de1-9b08-2aa63245788d</Id>
<AnnotationText>JOT_Sample</AnnotationText>
<IssueDate>2018-02-16T20:59:42-00:00</IssueDate>
<Issuer>Generic</Issuer>
<Creator>Generic</Creator>
<AssetList>
<Asset>
<Id>urn:uuid:744f36b7-fc7e-4179-8b75-c71c18f98156</Id>
<AnnotationText>Video_744f36b7-fc7e-4179-8b75-c71c18f98156.mxf</AnnotationText>
<Hash>8HhnKnLn+Lp/Ik9i94Ml4SXAxH4=</Hash>
<Size>14568486</Size>
<Type>application/mxf</Type>
<OriginalFileName>Video_744f36b7-fc7e-4179-8b75-c71c18f98156.mxf</OriginalFileName>
<HashAlgorithm Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
</Asset>
<Asset>
<Id>urn:uuid:bf5438ea-ba58-4ae0-a64a-5d23cee2ebb3</Id>
<AnnotationText>Audio_bf5438ea-ba58-4ae0-a64a-5d23cee2ebb3.mxf</AnnotationText>
<Hash>Wg4aEAE5Ji9e14ZyGkvfUUjBwCw=</Hash>
<Size>4341294</Size>
<Type>application/mxf</Type>
<OriginalFileName>Audio_bf5438ea-ba58-4ae0-a64a-5d23cee2ebb3.mxf</OriginalFileName>
<HashAlgorithm Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
</Asset>
</AssetList>
</PackingList>
XML (Output File)
<?xml version="1.0" encoding="UTF-8"?>
<PackingList xmlns="http://www.smpte-ra.org/schemas/2067-2/2016/PKL">
<Id>urn:uuid:296a656c-3610-4de1-9b08-2aa63245788d</Id>
<AnnotationText>JOT_Sample</AnnotationText>
<IssueDate>2018-02-16T20:59:42-00:00</IssueDate>
<Issuer>Generic</Issuer>
<Creator>Generic</Creator>
<AssetList>
<Asset>
<Id>urn:uuid:744f36b7-fc7e-4179-8b75-c71c18f98156</Id>
<AnnotationText>Video_744f36b7-fc7e-4179-8b75-c71c18f98156.mxf</AnnotationText>
<Hash>8HhnKnLn+Lp/Ik9i94Ml4SXAxH4=</Hash>
<Size>14568486</Size>
<Type>application/mxf</Type>
<OriginalFileName>Video_744f36b7-fc7e-4179-8b75-c71c18f98156.mxf</OriginalFileName>
<HashAlgorithm Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
</Asset>
<Asset>
<Id>urn:uuid:bf5438ea-ba58-4ae0-a64a-5d23cee2ebb3</Id>
<AnnotationText>Audio_bf5438ea-ba58-4ae0-a64a-5d23cee2ebb3.mxf</AnnotationText>
<Hash>Wg4aEAE5Ji9e14ZyGkvfUUjBwCw=</Hash>
<Size>4341294</Size>
<Type>application/mxf</Type>
<OriginalFileName>Audio_bf5438ea-ba58-4ae0-a64a-5d23cee2ebb3.mxf</OriginalFileName>
<HashAlgorithm Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
</Asset>
</AssetList>
</PackingList>
Code (partial):
XDocument pkldoc = XDocument.Load(packing, LoadOptions.PreserveWhitespace);
var pklns = pkldoc.Root.GetDefaultNamespace();
var pkluuid = pkldoc.Descendants(pklns + "Id").FirstOrDefault().Value;
var pklassetElements = pkldoc.Descendants(pklns + "Asset");
foreach (var pklasset in pklassetElements)
{
var idElement = pklasset.Descendants(pklns + "Id").First();
if (!idElement.Value.Equals(cpluuid))
continue;
SetNewValue(pklasset, pklns + "OriginalFileName", outfile);
}
void SetNewValue(XElement currentElement, XName elementName, string newValue)
{
var matchingElements = currentElement.Descendants(elementName);
if (matchingElements.Any())
{
foreach (var element in matchingElements)
element.SetValue(newValue);
}
}
pkldoc.Save(packing, SaveOptions.DisableFormatting);
FileInfo fi = new FileInfo(packing);
var pklsize = fi.Length;
This works, though not very clean on my part.
string text = File.ReadAllText(packing);
text = text.Replace(" />", "/>");
File.WriteAllText(packing, text);
UPDATE
This is the solution. Thanks you #asherber !
var textToSave = pkldoc.ToString(SaveOptions.DisableFormatting).Replace(" />", "/>");
File.WriteAllText(packing, textToSave);
I want the output to be like this:
<Order xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:gml="example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="example.com http://schemas.xyz.net/gml/2.1.2/feature.xsd"
xsi:noNamespaceSchemaLocation="http://www.xyz.co.uk/xmlorders3/lig_xml_orders.xsd">
The code I am using to get this is :
xmlDocument.DocumentElement.SetAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
xmlDocument.DocumentElement.SetAttribute("xmlns:gml", "example.com");
xmlDocument.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlDocument.DocumentElement.SetAttribute("xsi:schemaLocation", "example.com http://schemas.opengis.com/gml/2.1.2/feature.xsd");
xmlDocument.DocumentElement.SetAttribute("xsi:noNamespaceSchemaLocation","http://www. xyz.co.uk/xmlorders3/lig_xml_orders.xsd");
But I am getting the output like this :
<Order xmlns:gml="example.com" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
schemaLocation="example.com http://schemas.xyz.net/gml/2.1.2/feature.xsd"
noNamespaceSchemaLocation="http://www.xyz.co.uk/xmlorders3/lig_xml_orders.xsd">
Please suggest me any other way to get the required output.
You should use another version of SetAttribute method:
xmlDocument.DocumentElement
.SetAttribute("schemaLocation", "http://www.w3.org/2001/XMLSchema-instance", "example.com http://schemas.opengis.com/gml/2.1.2/feature.xsd");
i found way out. it may not be the best way. the solution is :
string xmlString = xmlDocument.InnerXml.ToString(); xmlString= xmlString.Replace("schemaLocation", "xsi:schemaLocation"); xmlString= xmlString.Replace("noNamespaceSchemaLocation", "xsi:noNamespaceSchemaLocation"); xmlDocument.LoadXml(xmlString);
// now i have the xmlDocument as i required.
I'm writing a configuration storage method for one of my clients and they requested that it be in XML. I've managed to get it to work other than one issue; the first element is missing. My XML file is:
<?xml version="1.0" encoding="utf-8" ?>
<config>
<username>test</username>
<password>pass</password>
<autologin>true</autologin>
</config>
My Parsing command is:
void parseConfigFile()
{
while (configstr.Read())
{
if (configstr.IsStartElement())
{
config.Add(configstr.Name,configstr.ReadString());
}
}
}
and the result (configstr) is:
autologin = true
config =
password = pass
var document = XDocument.Load("file.xml");
var config = document.Root;
var userName = (string)config.Element("username");
var password = (string)config.Element("password");
var autologin = (bool)config.Element("autologin");
I'm stuck with some task here. I want to write to xml file.
Here is the file:
<?xml version="1.0" encoding="utf-8"?>
<lists>
<plannedList>
<Skift-a></Skift-a>
<Skift-b></Skift-b>
<Skift-c></Skift-c>
<Skift-d></Skift-d>
<Skift-e></Skift-e>
</plannedList>
<requestedList>
<Skift-a></Skift-a>
<Skift-b></Skift-b>
<Skift-c></Skift-c>
<Skift-d></Skift-d>
<Skift-e></Skift-e>
</requestedList>
</lists>
then i want to use c# and for example dataset or an other method to add a jobID under the loggedIn Skift. so if Skift-a is logged on, and press a button, i want the xml file to look like this:
<?xml version="1.0" encoding="utf-8"?>
<lists>
<plannedList>
<Skift-a></Skift-a>
<Skift-b></Skift-b>
<Skift-c></Skift-c>
<Skift-d></Skift-d>
<Skift-e></Skift-e>
</plannedList>
<requestedList>
<Skift-a></Skift-a>
<jobID>1<jobID/>
<Skift-b></Skift-b>
<Skift-c></Skift-c>
<Skift-d></Skift-d>
<Skift-e></Skift-e>
</requestedList>
</lists>
And here is what I've tried so far:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(this.Page.Server.MapPath("~/StoredData/JobsByUsers.xml"));
XmlNode Skift = xmldoc.SelectSingleNode("/requestedList/" + User.Identity.Name.ToString());
XmlNode newJobID = xmldoc.CreateNode(XmlNodeType.Element, "jobID", null);
newJobID.InnerText = topID.ToString();
Skift.AppendChild(newJobID);
xmldoc.Save(this.Page.Server.MapPath("~/StoredData/JobsByUsers.xml"));
I have the following .xml file:
<?xml version="1.0" encoding="utf-8" ?>
<Params>
<Name>Resolver1</Name>
<RemoteHosts>
<Host>
<Name>Locale</Name>
<IP>localhost</IP>
<Port>8082</Port>
</Host>
</RemoteHosts>
</Params>
Now, when I try to add another "Host" in the "RemoteHosts" section using the following code it raises a NullReferenceException:
XDocument xmlList = XDocument.Load("NetConfig.xml");
xmlList.Element("RemoteHosts").Add(new XElement("Host",
new XElement("Name", h.name),
new XElement("IP", h.IP),
new XElement("Port", h.port)));
anyway the
xmlList.Save("NetConfig.xml");
works well, saving the new item...what's wrong?
XmlList contains only 1 node and its Params not RemoteHosts
Try xmlList.Root.Element("RemoteHosts")