The problem is the ServiceDocument as the xmlns attribute on it.
---Preassigned XML
System.Xml.XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>
<ServiceDocument
xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"
xmlns=\"http://schemas.microsoft.com/ado/2007/08/dataservices\"
>
<BaseUri>
http://xxxx.xxxxx.net/xxx.1/
</BaseUri>
<ProfilesLink>
http://adf.apis.dds.net/af.1/
</ProfilesLink>
<SignedInUser>
<Cid>
4433sfsdfgd
</Cid>
<Uri>
http://fd.apis.afdafd.net/V4.1/cid-xxxxx/adad
</Uri>
</SignedInUser>
<StatusMessageLink>
http://psm.adfa.afd.net/dfa.1/
</StatusMessageLink>
</ServiceDocument>"
);
// Response.Write(xmlDoc.InnerXml);
--//PARSE XML problem is below**
Response.Write(xmlDoc.SelectSingleNode("/ServiceDocument/BaseUri").InnerXml);
You need to assign short aliases to the namespaces using the XMLNamespaceManager.
See this page for an example.
So, to solve your problem:
var xmlNamespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
xmlNamespaceManager.AddNamespace("ds", "http://schemas.microsoft.com/ado/2007/08/dataservices");
var result = xmlDoc.SelectNodes("/ds:ServiceDocument/ds:BaseUri", xmlNamespaceManager);
Related
I would like to read a XML File with C#, but i always get an error.
This is my XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<OMDS xmlns="urn:omds20" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:omds20 ./omds26-00.xsd">
<PAKET VUNr="014" PaketZpktErstell="2014-08-29T10:45:08.575" PaketZpktLetztErstell="2014-08-29T10:45:08.575" PaketInhCd="VM" PaketUmfCd="G" VUVersion="26-00" DVRNrAbs="0">
<PERSON ....
<PERSON ....
<PERSON ....
I would like to read this XML, but XMLContentNodes is always null. So i am unable to get the SelectSingleNode with this Path, but i cant find out what should be wrong here?
XmlDocument doc = new XmlDocument();
doc.Load(openFileDialog1.FileName);
XmlNode XMLContentNodes = doc.SelectSingleNode("/OMDS/PAKET"); // Error Here
XmlNodeList PersonNodeList = XMLContentNodes.SelectNodes("PERSON");
foreach (XmlNode node in PersonNodeList)
{
.....
Any help would be greatly appreciated.
The usual namespace problem. Try
XmlNamespaceManager mgr = new XmlNamespaceManager(new NameTable());
mgr.AddNamespace("d", "urn:omds20");
XmlNode XMLContentNodes = doc.SelectSingleNode("/d:OMDS/d:PAKET", mgr);
XmlNodeList PersonNodeList = XMLContentNodes.SelectNodes("d:PERSON", mgr);
You'll need to add the namespace urn:omds20 to the doc XmlDocument object after loading your XML file in it. It will look like the following:
XmlDocument doc = new XmlDocument();
doc.Load(openFileDialog1.FileName);
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(doc.NameTable);
xmlnsManager.AddNamespace("omds20", "urn:omds20");
Then you can query for the PAKET node like this:
XmlNode paketNode = doc.SelectSingleNode("/omds20:OMDS/omds20:PAKET", xmlnsManager);
Using C#2.0 and VIsualStudio2005
I'm trying to access the "DisplayName" inside "MonitorResponseRecord"
from an XML file like the one Below:
<Magellan xsi:schemaLocation="http://tempuri.org/XMLSchema.xsd ..\Schema\Configuration.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/XMLSchema.xsd">
<SchemaVersion>1.0</SchemaVersion>
<MonitorScope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="CleanStationChemicalManifoldFeed5" xmlns="http://tempuri.org/XMLSchema.xsd">
<PersonalSafety>
<MonitorResponseRecord Enabled="true" DisplayName="ChemicalManifoldFeed5ControllerFault">
<ExpressionMonitor>
<Expression>(ChemicalManifold.Feed5.DispenseValve = Open) and ((ChemicalManifold.Feed5.ViolatedRegion = HighProcess) or (ChemicalManifold.Feed5.ViolatedRegion = LowProcess) or (ChemicalManifold.Feed5.ViolatedRegion = Minimum))</Expression>
<TestInterval>0.1</TestInterval>
<MinimumTimeBetweenResponses>5</MinimumTimeBetweenResponses>
</ExpressionMonitor>
<Response>
<PostAlarm>
<AlarmName>ChemicalManifold_Feed5_ControllerFault</AlarmName>
<Parameter1 />
<Parameter2>Alarm Region = {ChemicalManifold.Feed5.ViolatedRegion}</Parameter2>
<Parameter3>{RecipeName}-{StepName}</Parameter3>
<Parameter4>FlowSetpoint = {ChemicalManifold.Feed5.Setpoint}-LPM, ActualFlow = {ChemicalManifold.Feed5.FlowMeter}-LPM</Parameter4>
</PostAlarm>
<ResponseEvent>
<TargetResource />
<Event>PA</Event>
<Reason>ChemicalSupply</Reason>
</ResponseEvent>
</Response>
</MonitorResponseRecord>
</PersonalSafety>
<PersonalSafety>
<MonitorResponseRecord Enabled="true" DisplayName = "PressureValveFailure">
...
...
...and soon
My current C# attempt is as follows, BUT it always hangs up when I try to XmlDocument.Load("");
XmlDocument doc = new XmlDocument();
doc.Load("../UMC0009.Configuration.Root.xml");
string attrVal = doc.SelectSingleNode("MonitorResponseRecord/#DisplayName").Value;
BUUUUT won't work :/ any help out there?
UPDATE:
the exception I recieve is as follows, and occures at the doc.Load("...") line:
{"Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function."} System.Exception {System.Xml.XPath.XPathException}
Your XPath query will be relative to the document root:
doc.SelectSingleNode("MonitorResponseRecord/#DisplayName")
To make it search anywhere in the doc prefix it with double slash:
doc.SelectSingleNode("//MonitorResponseRecord/#DisplayName")
If that still doesn't work I would try the above example after stripping out all those namespace declarations on the two root nodes.
Otherwise, with the namespace declarations you may find you need to define XML namespace mappings and use prefixes in your XPath like:
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("x", "http://tempuri.org/XMLSchema.xsd");
doc.SelectSingleNode("//x:MonitorResponseRecord/#DisplayName")
What about:
XmlDocument doc = new XmlDocument();
doc.Load("UMC0009.Configuration.Root.xml");
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ns", "http://tempuri.org/XMLSchema.xsd");
string attrVal = doc.SelectSingleNode("//ns:MonitorResponseRecord/#DisplayName", nsmgr).Value;
Using a namespace manager, specify your namespace URI and use it in your XPath.
It works for me.
XmlElement xmlElementSAPD = xmlDocument.CreateElement("SAPD");
root.AppendChild(xmlElementSAPD);
xmlElementSAPD.AppendChild(XmlFunctions.GetXMLElement(xmlDocument, "smu", dr.GetString("sma").Trim()));
The c# code above creates XML below.
<SAPD>
<smu>123</smu>
</SAPD>
How can I change the code above so that I can get
<ns0:SAPD>
<ns0:smu>123</ns0:smu>
</ns0:SAPD>
Anyone? How can I add ns0: in xml nodes?
You have to add the namespace to your xml document.
Just to give you an idea have a look at the below
XmlDocument doc = new XmlDocument();
XmlSchema schema = new XmlSchema();
schema.Namespaces.Add("ns0", "http://www.sample.com/file");
doc.Schemas.Add(schema);
You prefix ns0 needs to be mapped with a namespace else the xml would not be valid.
Assumning ns0 is mapped to http://tempuri.org the below code can be used:
XmlDocument doc = new XmlDocument();
XmlElement sapd= doc.CreateElement("ns0","SAPD","http://tempuri.org");
XmlElement smu = doc.CreateElement("ns0", "smu", "http://tempuri.org");
smu.InnerText = "123";
sapd.AppendChild(smu);
doc.AppendChild(sapd);
doc.InnerXml.ToString();
I have XML stored in string variable:
<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>
Here I want to change XML tag <ItemMasterList> to <Masterlist>. How can I do this?
System.Xml.XmlDocument and the associated classes in that same namespace will prove invaluable to you here.
XmlDocument doc = new XmlDocument();
doc.LoadXml(yourString);
XmlDocument docNew = new XmlDocument();
XmlElement newRoot = docNew.CreateElement("MasterList");
docNew.AppendChild(newRoot);
newRoot.InnerXml = doc.DocumentElement.InnerXml;
String xml = docNew.OuterXml;
I know i am a bit late, but just have to add this answer as no one seems to know about this.
XDocument doc = XDocument.Parse("<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>");
doc.Root.Name = "MasterList";
Which returns the following:
<MasterList>
<ItemMaster>
<fpartno>xxx</fpartno>
<frev>000</frev>
<fac>Default</fac>
</ItemMaster>
</MasterList>
You can use LINQ to XML to parse the XML string, create a new root and add the child elements and attributes of the original root to the new root:
XDocument doc = XDocument.Parse("<ItemMasterList>...</ItemMasterList>");
XDocument result = new XDocument(
new XElement("Masterlist", doc.Root.Attributes(), doc.Root.Nodes()));
Using the XmlDocument way, you can do this as follows (and keep the tree intact):
XmlDocument oldDoc = new XmlDocument();
oldDoc.LoadXml("<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>");
XmlNode node = oldDoc.SelectSingleNode("ItemMasterList");
XmlDocument newDoc = new XmlDocument();
XmlElement ele = newDoc.CreateElement("MasterList");
ele.InnerXml = node.InnerXml;
If you now use ele.OuterXml is will return: (you you just need the string, otherwise use XmlDocument.AppendChild(ele) and you will be able to use the XmlDocument object some more)
<MasterList>
<ItemMaster>
<fpartno>xxx</fpartno>
<frev>000</frev>
<fac>Default</fac>
</ItemMaster>
</MasterList>
As pointed by Will A, we can do it that way but for case where InnerXml equals the OuterXml the following solution will work out:
// Create a new Xml doc object with root node as "NewRootNode" and
// copy the inner content from old doc object using the LastChild.
XmlDocument docNew = new XmlDocument();
XmlElement newRoot = docNew.CreateElement("NewRootNode");
docNew.AppendChild(newRoot);
// The below line solves the InnerXml equals the OuterXml Problem
newRoot.InnerXml = oldDoc.LastChild.InnerXml;
string xmlText = docNew.OuterXml;
My code doesn't return the node
XmlDocument xml = new XmlDocument();
xml.InnerXml = text;
XmlNode node_ = xml.SelectSingleNode(node);
return node_.InnerText; // node_ = null !
I'm pretty sure my XML and Xpath are correct.
My Xpath : /ItemLookupResponse/OperationRequest/RequestId
My XML :
<?xml version="1.0"?>
<ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
<OperationRequest>
<RequestId>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx</RequestId>
<!-- the rest of the xml is irrelevant -->
</OperationRequest>
</ItemLookupResponse>
The node my XPath returns is always null for some reason. Can someone help?
Your XPath is almost correct - it just doesn't take into account the default XML namespace on the root node!
<ItemLookupResponse
xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
*** you need to respect this namespace ***
You need to take that into account and change your code like this:
XmlDocument xml = new XmlDocument();
xml.InnerXml = text;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("x", "http://webservices.amazon.com/AWSECommerceService/2005-10-05");
XmlNode node_ = xml.SelectSingleNode(node, nsmgr);
And then your XPath ought to be:
/x:ItemLookupResponse/x:OperationRequest/x:RequestId
Now, your node_.InnerText should definitely not be NULL anymore!
Sorry for the late reply but I had a similar problem just a moment ago.
if you REALLY want to ignore that namespace then just delete it from the string you use to initialise the XmlDocument
text=text.Replace(
"<ItemLookupResponse xmlns=\"http://webservices.amazon.com/AWSECommerceService/2005-10-05\">",
"<ItemLookupResponse>");
XmlDocument xml = new XmlDocument();
xml.InnerXml = text;
XmlNode node_ = xml.SelectSingleNode(node);
return node_.InnerText;