Append subchildnode - c#

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"));

Related

Unable to get element in XML

<?xml version="1.0" encoding="utf-8"?>
<serv:message
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:serv="http://www.webex.com/schemas/2002/06/service" xsi:schemaLocation="http://www.webex.com/schemas/2002/06/service http://www.webex.com/schemas/2002/06/service.xsd">
<header>
<securityContext>
<webExID/>
<password/>
<siteID/>
<partnerID/>
</securityContext>
</header>
<body>
<bodyContent xsi:type="java:com.webex.service.binding.training.CreateTrainingSession"
xmlns="http://www.webex.com/schemas/2002/06/service/training"
xmlns:com="http://www.webex.com/schemas/2002/06/common"
xmlns:sess="http://www.webex.com/schemas/2002/06/session"
xmlns:serv="http://www.webex.com/schemas/2002/06/service"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.webex.com/schemas/2002/06/service/training http://www.webex.com/schemas/2002/06/service/training/trainingsession.xsd">
<sess:accessControl>
<sess:sessionPassword/>
</sess:accessControl>
<sess:schedule></sess:schedule>
<metaData>
<sess:confName/>
<agenda/>
<description/>
<greeting/>
<location/>
</metaData>
<enableOptions>
<chat/>
<poll/>
<audioVideo/>
<fileShare/>
<applicationShare/>
<desktopShare/>
<annotation/>
<fullScreen/>
<voip/>
</enableOptions>
</bodyContent>
</body>
</serv:message>
Above XML is standard VILT Create Event xml and I need to populate it with proper data.
The issue is I am able to get "securityContent" element using below code and node holds total count of child elements that is 4:
var node = xmlDoc.SelectNodes("/serv:message/header/securityContext/*", GetNameSpace(xmlDoc.NameTable));
But when I try to get another node i.e. "metaData" then I get Count 0 and way to getting element is exactly same except the path to the element.
Below is sample code that I've tried but not working:
static void Main(string[] args)
{
var xmlPathh = #"C:\Users\SKMEENA\Desktop\VILT.xml";// this holds above xml
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPathh);
var node = xmlDoc.SelectNodes("/serv:message/header/securityContext/*", GetNameSpace(xmlDoc.NameTable));
var member = xmlDoc.SelectNodes("/serv:message/body/bodyContent/metaData/*", GetNameSpace(xmlDoc.NameTable));
}
static XmlNamespaceManager GetNameSpace(XmlNameTable objNameTable)
{
XmlNamespaceManager objNsManager =new XmlNamespaceManager(objNameTable);
objNsManager.AddNamespace("serv", "http://www.webex.com/schemas/2002/06/service");
objNsManager.AddNamespace("ns1", "http://www.webex.com/schemas/2002/06/service/site");
return objNsManager;
}
Anybody has any idea what is wrong with above code and how can I make it working?
The bodyContent node has a default namespace which applies to it and all its children.
You need to add it to the NamespaceManager and then use it in the XPath
var member = xmlDoc.SelectSingleNode("/serv:message/body/body:bodyContent/body:metaData", GetNameSpace(xmlDoc.NameTable));
member.OuterXml.Dump();
static XmlNamespaceManager GetNameSpace(XmlNameTable objNameTable)
{
XmlNamespaceManager objNsManager =new XmlNamespaceManager(objNameTable);
objNsManager.AddNamespace("serv", "http://www.webex.com/schemas/2002/06/service");
objNsManager.AddNamespace("ns1", "http://www.webex.com/schemas/2002/06/service/site");
objNsManager.AddNamespace("body", "http://www.webex.com/schemas/2002/06/service/training");
objNsManager.AddNamespace("sess","http://www.webex.com/schemas/2002/06/session");
return objNsManager;
}
dotnetfiddle

Copy XML nodes to another XML includes child nodes

I need to create another xml whenever there is numerics in the zipname and move those related nodes to another xml
Actual XML :
<?xml version="1.0"?>
-<IMAGE date="20200603" Time="141511">
-<ZipFile name="something.zip" Date="06032020" Time="131511">
<name="015522000970" line="001" status="STORED" />
<name="015522000990" line="002" status="STORED" />
</ZipFile>
-<ZipFile name="something111.zip" Date="06032020" Time="131511">
<name="015522000970" line="001" status="STORED" />
<name="015522000990" line="002" status="STORED" />
</ZipFile>
</IMAGE>
Result xml (Newone need tobe created):
<?xml version="1.0"?>
-<IMAGE date="20200603" Time="141511">
-<ZipFile name="something111.zip" Date="06032020" Time="131511">
<name="015522000970" line="001" status="STORED" />
<name="015522000990" line="002" status="STORED" />
</ZipFile>
</IMAGE>
here is my code but it is not working . could anyone provide the approach how to copy
XmlNodeList xmlNodeList = xmlDoc.GetElementsByTagName(XML_ZIPFILETAG);
foreach (XmlNode node in xmlNodeList)
{
XmlDocument xmkdoc1 = new XmlDocument();
XmlNode copiedNode = xmlDoc.ImportNode(node,true);
//SelectSingleNode(#"/Image/ZipFileName");
// node.InnerXml;
XmlNode root = xmkdoc1.DocumentElement;
xmkdoc1.CreateElement("DocumentElemnet");
xmkdoc1.AppendChild(copiedNode);
}
You are quite close. When constructing the new document you need to build up the structure correctly. Try this (I did not test the code):
XmlDocument xmkdoc1 = new XmlDocument();
XmlNode root = xmkdoc1.createElement(XML_ZIPFILETAG);
xmkdoc1.AppendChild(root);
XmlNode copiedNode = xmlDoc.ImportNode(node,true);
root.AppendChild(copiedNode);

Exception while reading XML - "Namespace Manager or XsltContext needed"

My xml is as below
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="../../config/janes-deliver.xsl"?>
<!DOCTYPE janes:record SYSTEM "../../config/janesml-delivery-norm-2.1.dtd">
<janes:record xmlns:janes="http://dtd.janes.com/2002/Content/" id="j1891356689831320" pubabbrev="JIQ" sysId="JIQ0105" urname="record">
<janes:metadata xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="j1891356689831320" urname="metadata" xlink:type="simple">
<dc:rights xmlns:dc="http://purl.org/dc/elements/1.1/">Copyright © IHS Global Limited, 2014</dc:rights>
<dc:date xmlns:dc="http://purl.org/dc/elements/1.1/" qualifier="pubDate">30000101</dc:date>
<dc:date xmlns:dc="http://purl.org/dc/elements/1.1/" qualifier="postDate">20140822</dc:date>
<janes:title urname="title">IHS Jane's Navigating the Emerging Markets</janes:title>
<janes:shortTitle urname="shortTitle">Canada</janes:shortTitle>
<janes:sect1 id="j18967561358768718373" urname="sect1">
<janes:para id="j18967561358768718388" urname="para"><janes:link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="jiq0105_a.pdf" qualifier="pdf" urname="link" xlink:type="simple"><janes:linkText urname="linkText">Please click here for the full PDF report.</janes:linkText></janes:link></janes:para>
</janes:sect1>
<janes:sect1 id="j26330201380885096083" updated="y" urname="sect1">
<janes:title urname="title">Military inventories</janes:title>
.......................
I need to retrieve the contents of the tag
I have written a code like below
XmlDocument doc = new XmlDocument();
doc.Load(filepath);
foreach (XmlNode node in doc.SelectNodes("janes:link"))
{
string name = node.Name;
string value = node.InnerText;
// ...
}
I am getting the error "Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function."
Can Some one help ?
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(filepath);
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("janes", "http://dtd.janes.com/2002/Content/");
foreach (XmlNode node in doc.SelectNodes(#"//janes:link", nsmgr))
{
//...
}
This answers explains why XmlNamespaceManager is needed.

output XML to dataset

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);
}

XMLTextReader missing first element

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");

Categories