XPATH preceding node - c#

I have following XML:
XML
<PatientDetailsXML>
<PList>
<PName type="Patient"> // node [i] = 0
<properties>
<Room bedType="Auto" />
<PName title="Joe Beom" PId="1234">
<Details>
<classification classification="paymenttype" category="Wallet" />
<classification classification="Humor" category="1" />
<classification classification="Food" category="Fruit" />
</Details>
</PName>
</properties>
<childEvents>
</childEvents>
</PName>
<PName type="Patient"> // node[i] =1
<properties>
<Room bedType="Auto" />
<PName title="John Bair" PId="4567">
<Details>
<classification classification="paymenttype" category="Wallet" />
<classification classification="Humor" category="2" />
<classification classification="Food" category="Fruit" />
</Details>
</PName>
</properties>
<childEvents>
</childEvents>
</PName>
<PName type="Patient"> // node[i] = 2
<properties>
<Room bedType="Auto" />
<PName title="Bairstow" PId="1234">
<Details>
<classification classification="paymenttype" category="CreditCard" />
<classification classification="Humor" category="1" />
<classification classification="Food" category="Vegetables" />
</Details>
</PName>
</properties>
<childEvents>
</childEvents>
</PName>
When I'm at node[0], i'm doing a search for classification='paymenttype' and category ='CreditCard', I find the 3rd item node[i] = 2
var next = currNode.SelectSingleNode(#"following::classifications/classification[#classification='paymenttype'and #category ='CreditCard'] /ancestor::PName/#title"); // This gives me the title `Bairstow`
Now I need to jump to my previous node where classification='paymenttype'and #category ='CreditCard'.
var previous = next.SelectSingleNode(#"preceding::classifications/classification[#classification='paymenttype'and #category ='CreditCard']/ancestor::event");
// this doesn't seem to work
CODE
var query = #"//PList/PName[.//PName/classifications/classification[#classification='paymenttype' and #category='Wallet']]";
var nodes = docs.SelectNodes(query).OfType<XmlNode>().ToArray();
XmlNodeList nodeList = docs.SelectNodes(query);
for (int i = 0; i < nodes.Count(); i++)
{
//do something
//jump to method to do something else
string testPayment = Externals.Next(nodes[i]);
}
public static string Next(XMLNode currNode)
{
var next = currNode.SelectSingleNode(#"following::classifications/classification[#classification='Humor'and #category ='1'] /ancestor::PName/#title");
// This gives me the title `Bairstow`
// Now I need to select the title of the previous node e.g.John Bair
var previous = next.SelectSingleNode(#"preceding::classifications/classification[#classification='paymenttype'and #category ='CreditCard']/ancestor::event");
// this is not pointing to the node with title JohnBair
}

Related

inserting a node after a specific node in xml file

i'm re posting my question in a simpler way.
i need to search for a specific node in a XML file, and once i see it, i need to create a new node and insert it after that. the problem is that there are 2 nodes with the same value. and i need to insert the new node twice after each instance. with the code below: it's inserting the new nodes twice but in the same place after the first instance only.
original XML:
<eventlist>
<event type="AUDIOPLAYER">
<properties>
<schedule startType="-ParentEnd1" />
<media mediaType="Audio" />
</properties>
</event>
<event type="AUDIOPLAYER">
<properties>
<schedule startType="-ParentEnd2" />
<media mediaType="Audio" />
</properties>
</event>
</eventlist>
intended XML:
<eventlist>
<event type="AUDIOPLAYER">
<properties>
<schedule startType="-ParentEnd1" />
<media mediaType="Audio" />
</properties>
</event>
<event type="VIZ" />
<event type="AUDIOPLAYER">
<properties>
<schedule startType="-ParentEnd2" />
<media mediaType="Audio" />
</properties>
</event>
<event type="VIZ" />
</eventlist>
but the current output is:
<eventlist>
<event type="AUDIOPLAYER">
<properties>
<schedule startType="-ParentEnd1" />
<media mediaType="Audio" />
</properties>
</event>
<event type="VIZ" />
<event type="VIZ" />
<event type="AUDIOPLAYER">
<properties>
<schedule startType="-ParentEnd2" />
<media mediaType="Audio" />
</properties>
</event>
</eventlist>
the code is below here:
XmlDocument xdoc = new XmlDocument();
xdoc.Load(#"C:\Users\namokhtar\Desktop\newxml\testxml.xml");
foreach (XmlNode node in xdoc.SelectNodes("/eventlist/event[#type='AUDIOPLAYER']"))
{
XmlNode srcNode = node.SelectSingleNode("/eventlist/event[#type='AUDIOPLAYER']");
XmlNode newElem = xdoc.CreateElement("event");
XmlAttribute newAttr = xdoc.CreateAttribute("type");
newAttr.Value = "VIZ";
newElem.Attributes.Append(newAttr);
srcNode.ParentNode.InsertAfter(newElem, srcNode);
}
xdoc.Save(#"C:\Users\namokhtar\Desktop\newxml\newxml1.xml");
please advise me...
I haven´t fully tested this, but I´m almost sure this should do the trick:
foreach (XmlNode node in xdoc.SelectNodes("/eventlist/event[#type='AUDIOPLAYER']"))
{
XmlNodeList srcNodes = node.SelectNodes("/eventlist/event[#type='AUDIOPLAYER']");
foreach (XmlNode srcNode in srcNodes)
{
XmlNode newElem = xdoc.CreateElement("event");
XmlAttribute newAttr = xdoc.CreateAttribute("type");
newAttr.Value = "VIZ";
newElem.Attributes.Append(newAttr);
srcNode.ParentNode.InsertAfter(newElem, srcNode);
}
}
The problem is you were selecting single node from matching expression, and you need to select all the nodes that match that and insert the new node after each of them.
Hope this helps!
Here is a solution using LINQ:
var xml = XDocument.Parse(File.ReadAllText(#"C:\Users\namokhtar\Desktop\newxml\testxml.xml"));
var elems = xml.Root.Elements()
.Where(e => e.Name == "event" && e.Attribute("type")?.Value == "AUDIOPLAYER");
foreach (var elem in elems)
{
elem.AddAfterSelf(new XElement("event", new XAttribute("type", "VIZ")));
}
xml.Save(#"C:\Users\namokhtar\Desktop\newxml\newxml1.xml");

Checking for Last Node

I have the following xml. How do I test for last node?
<PatientDetailsXML>
<PList>
<PName type="Patient">
<properties>
<Room bedType="Auto" />
<PName title="Joe Beom" PId="1234">
<Details>
<classification classification="paymenttype" category="Wallet" />
<classification classification="Humor" category="None" />
<classification classification="Food" category="Fruit" />
</Details>
</PName>
</properties>
<childEvents>
</childEvents>
</PName>
<PName type="Patient">
<properties>
<Room bedType="Auto" />
<PName title="John Bair" PId="1234">
<Details>
<classification classification="paymenttype" category="Found" />
<classification classification="Humor" category="None" />
<classification classification="Food" category="Fruit" />
</Details>
</PName>
</properties>
<childEvents>
</childEvents>
</PName>
<!-- End of List -->
</PList>
</PatientDetailsXML>
During the for loop I end up <!-- End of List -->, I do a test for the comment but then I need to also test if there is no node after that.
var nodes = docs.SelectNodes(query).OfType<XmlNode>().ToArray();
XmlNodeList nodeList = docs.SelectNodes(query);
for (int i = 0; i < nodes.Count(); i++)
{
XmlNode multinextnode = nodes[i];
if (multinextnodetest == "#comment")
{
multinextnode.NextSibling;
{
if (multinextnode.Equals(multinextnode.LastChild))
{
Console.WriteLine("final");
}
// some code
}
}
// somecode
}
This multinextnode.Equals(multinextnode.LastChild) doesn't seem to work for me. In the for loop I'm jumping to next node as you can see above multinextnode.NextSibling. This is absolutely necessary to achieve my target with the code. But during the jump I may hit a null in the multinextnode. Which means there is no child/sibling/node after that, right before </PList>. So I need to do a test for lastchild
Right now I'm simply doing a null test and getting the job done. But I need to know if there is a better way.

c# linq selection of Element by selecting an child.child.attribute

I want to select one < NodeLabel > Tag. Selection should be done, when the < NodeLabel > has Elements.
The xml File looks like
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:java="http://www.yworks.com/xml/yfiles-common/1.0/java" xmlns:sys="http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0" xmlns:x="http://www.yworks.com/xml/yfiles-common/markup/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xmlns:yed="http://www.yworks.com/xml/yed/3" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">
<!--Created by yEd 3.14.2-->
<key attr.name="description" attr.type="string" for="graph" id="d0" />
<key for="port" id="d1" yfiles.type="portgraphics" />
<key for="port" id="d2" yfiles.type="portgeometry" />
<key for="port" id="d3" yfiles.type="portuserdata" />
<key attr.name="url" attr.type="string" for="node" id="d4" />
<key attr.name="description" attr.type="string" for="node" id="d5" />
<key for="node" id="d6" yfiles.type="nodegraphics" />
<key for="graphml" id="d7" yfiles.type="resources" />
<key for="edge" id="d8" yfiles.type="portconstraints" />
<key attr.name="url" attr.type="string" for="edge" id="d9" />
<key attr.name="description" attr.type="string" for="edge" id="d10" />
<key for="edge" id="d11" yfiles.type="edgegraphics" />
<graph edgedefault="directed" id="G">
<data key="d0" />
<node id="n0" yfiles.foldertype="group">
<data key="d6">
<y:TableNode configuration="YED_TABLE_NODE">
<y:Geometry height="646.8359897640048" width="1012.9110704527719" x="0.0" y="-646.8359897640048" />
<y:Fill color="#ECF5FF" color2="#0042F440" transparent="false" />
<y:BorderStyle color="#000000" type="line" width="1.0" />
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="15" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="22.37646484375" modelName="internal" modelPosition="t" textColor="#000000" visible="true" width="230.7578125" x="391.07662897638596" y="4.0">title</y:NodeLabel>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="custom" textColor="#000000" visible="true" width="54.712890625" x="111.14444510514247" y="33.0">col0<y:LabelModel><y:ColumnNodeLabelModel offset="3.0" /></y:LabelModel><y:ModelParameter><y:ColumnNodeLabelModelParameter id="column_0" inside="true" verticalPosition="0.0" /></y:ModelParameter></y:NodeLabel>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="custom" textColor="#000000" visible="true" width="72.712890625" x="482.3174666703262" y="33.0">col1<y:LabelModel><y:ColumnNodeLabelModel offset="3.0" /></y:LabelModel><y:ModelParameter><y:ColumnNodeLabelModelParameter id="column_1" inside="true" verticalPosition="0.0" /></y:ModelParameter></y:NodeLabel>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="custom" textColor="#000000" visible="true" width="58.046875" x="869.6051192915697" y="33.0">col2<y:LabelModel><y:ColumnNodeLabelModel offset="3.0" /></y:LabelModel><y:ModelParameter><y:ColumnNodeLabelModelParameter id="column_2" inside="true" verticalPosition="0.0" /></y:ModelParameter></y:NodeLabel>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="custom" rotationAngle="270.0" textColor="#000000" visible="true" width="40.01171875" x="3.0" y="330.4121355070024">row0<y:LabelModel><y:RowNodeLabelModel offset="3.0" /></y:LabelModel><y:ModelParameter><y:RowNodeLabelModelParameter horizontalPosition="0.0" id="row_0" inside="true" /></y:ModelParameter></y:NodeLabel>
<y:StyleProperties>
...
I just want to select < NodeLabel > Tag with the descendants("y:RowNodeLabelModelParameter").attribute("id").value = "row_0"
So far so easy.
I tried with the following code
XElement TableNode = yedFile.Descendants(y + "TableNode").FirstOrDefault();
XElement NodeLblRow = new XElement(TableNode.Elements(y + "NodeLabel")
.Where(t => t.HasElements )
.Where(x => x.Element(y + "ModelParameter")
.Element(y + "RowNodeLabelModelParameter")
.Attribute("id").Value == "row_0"
).FirstOrDefault()
);
but in the second where I get an NullReferenceException. What is missing? These are my first tries with linq and c# so it may be that I'am thinking to complicated. I think the problem occurs, because the first < NodeLabel > Tag has no child's. That's why I divided the selection in to "Where". The first one should select only the < NodeLabel > Tag's with child's an the second one should exactly match the last < NodeLabel > Tag. So far my intention.
Can someone give me a hint?
Thank you very much for your ideas and help.
For information:
I use the following namespaces
XNamespace xmlns = XNamespace.Get("http://graphml.graphdrawing.org/xmlns");
XNamespace /*xmlns:*/java = XNamespace.Get("http://www.yworks.com/xml/yfiles-common/1.0/java");
XNamespace /*xmlns:*/sys = XNamespace.Get("http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0");
XNamespace /*xmlns:*/x = XNamespace.Get("http://www.yworks.com/xml/yfiles-common/markup/2.0");
XNamespace /*xmlns:*/xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
XNamespace /*xmlns:*/y = XNamespace.Get("http://www.yworks.com/xml/graphml");
XNamespace /*xmlns:*/yed = XNamespace.Get("http://www.yworks.com/xml/yed/3");
You will get a null reference exception when you come across an element that doesn't have elements or attributes that make up your query.
By sticking with IEnumerable rather than 'exiting the monad' and making use of explicit conversions you can avoid having to do null checks, for example:
var element = yedFile.Descendants(y + "NodeLabel")
.FirstOrDefault(e => (string)e.Elements(y + "ModelParameter")
.Elements(y + "RowNodeLabelModelParameter")
.Attributes("id")
.SingleOrDefault() == "row_0");

No response in AG-Softwate MatriX

I am developing a IM by AG-Softwate MatriX and I want to achieve the login opertion, however when I use xmppClient.open(), I can't receive the xml stream that help me to accept the certificate.
this is the xml I have sended or received or output in console:
send:<stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" to="dodo.com" version="1.0" >
rec:<stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" id="2543867956" from="dodo.com" version="1.0" xml:lang="en" >
'vivid.vshost.exe' (CLR v4.0.30319: vivid.vshost.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.resources\v4.0_4.0.0.0_zh-Hans_b77a5c561934e089\System.resources.dll'. Module was built without symbols.
rec:<stream:features xmlns:stream="http://etherx.jabber.org/streams">
<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls" />
<mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
<mechanism>PLAIN</mechanism>
<mechanism>DIGEST-MD5</mechanism>
<mechanism>SCRAM-SHA-1</mechanism>
</mechanisms>
<c xmlns="http://jabber.org/protocol/caps" hash="sha-1" node="http://www.process-one.net/en/ejabberd/" ver="k0acyvEdZQ7cl5uD5FTPoiOnuaw=" />
<register xmlns="http://jabber.org/features/iq-register" />
</stream:features>
send:<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls" />
rec:<proceed xmlns="urn:ietf:params:xml:ns:xmpp-tls" />
I don't know why my program have not sended the rest xml, and you can see the right xml stream:
SEND: <stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" to="dodo.com" version="1.0" >
RECV: <stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" id="3880372647" from="dodo.com" version="1.0" xml:lang="en" >
RECV: <stream:features xmlns:stream="http://etherx.jabber.org/streams">
<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls" />
<mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
<mechanism>PLAIN</mechanism>
<mechanism>DIGEST-MD5</mechanism>
<mechanism>SCRAM-SHA-1</mechanism>
</mechanisms>
<c xmlns="http://jabber.org/protocol/caps" hash="sha-1" node="http://www.process-one.net/en/ejabberd/" ver="k0acyvEdZQ7cl5uD5FTPoiOnuaw=" />
<register xmlns="http://jabber.org/features/iq-register" />
</stream:features>
SEND: <starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls" />
RECV: <proceed xmlns="urn:ietf:params:xml:ns:xmpp-tls" />
SEND: <stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" to="dodo.com" version="1.0" >
RECV: <stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" id="2091441686" from="dodo.com" version="1.0" xml:lang="en" >
RECV: <stream:features xmlns:stream="http://etherx.jabber.org/streams">
<mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
<mechanism>PLAIN</mechanism>
<mechanism>DIGEST-MD5</mechanism>
<mechanism>SCRAM-SHA-1</mechanism>
</mechanisms>
<c xmlns="http://jabber.org/protocol/caps" hash="sha-1" node="http://www.process-one.net/en/ejabberd/" ver="k0acyvEdZQ7cl5uD5FTPoiOnuaw=" />
<register xmlns="http://jabber.org/features/iq-register" />
</stream:features>
SEND: <auth mechanism="SCRAM-SHA-1" xmlns="urn:ietf:params:xml:ns:xmpp-sasl">biwsbj1pbWFjLHI9NmJkdG40NWdGbTNoYWJIR3JpdGdnOUdqT21yUDU0alA=</auth>
RECV: <challenge xmlns="urn:ietf:params:xml:ns:xmpp-sasl">cj02YmR0bjQ1Z0ZtM2hhYkhHcml0Z2c5R2pPbXJQNTRqUGFqRWRPa0hKUGRCczl4aWMxN3lSeXc9PSxzPWowdHhSY0pnY0FaUkdYcnpCMUJydmc9PSxpPTQwOTY=</challenge>
SEND: <response xmlns="urn:ietf:params:xml:ns:xmpp-sasl">Yz1iaXdzLHI9NmJkdG40NWdGbTNoYWJIR3JpdGdnOUdqT21yUDU0alBhakVkT2tISlBkQnM5eGljMTd5Unl3PT0scD0weDZXcFJ1WG0vQzF5a3JIUXA1c2lBS2lpbzA9</response>
RECV: <success xmlns="urn:ietf:params:xml:ns:xmpp-sasl">dj1CRitFMkdhcVZLYlRVeHpLbWxwVG82YVpDZzQ9</success>
SEND: <stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" to="dodo.com" version="1.0" >
RECV: <stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" id="3562760347" from="dodo.com" version="1.0" xml:lang="en" >
RECV: <stream:features xmlns:stream="http://etherx.jabber.org/streams">
<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind" />
<session xmlns="urn:ietf:params:xml:ns:xmpp-session" />
<sm xmlns="urn:xmpp:sm:2" />
<sm xmlns="urn:xmpp:sm:3" />
<c xmlns="http://jabber.org/protocol/caps" hash="sha-1" node="http://www.process-one.net/en/ejabberd/" ver="k0acyvEdZQ7cl5uD5FTPoiOnuaw=" />
<register xmlns="http://jabber.org/features/iq-register" />
</stream:features>
SEND: <iq id="MX_1" type="set" xmlns="jabber:client">
<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">
<resource>MatriX</resource>
</bind>
</iq>
RECV: <iq id="MX_1" type="result" xmlns="jabber:client">
<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">
<jid>imac#dodo.com/MatriX</jid>
</bind>
</iq>
SEND: <iq id="MX_2" type="set" xmlns="jabber:client">
<session xmlns="urn:ietf:params:xml:ns:xmpp-session" />
</iq>
RECV: <iq type="result" id="MX_2" xmlns="jabber:client" />
SEND: <iq id="MX_3" type="get" xmlns="jabber:client">
<query xmlns="jabber:iq:roster" />
</iq>
RECV: <iq from="imac#dodo.com" to="imac#dodo.com/MatriX" id="MX_3" type="result" xmlns="jabber:client">
<query xmlns="jabber:iq:roster">
<item subscription="both" jid="test2#dodo.com">
<group>EveryBody</group>
</item>
<item subscription="both" jid="123456#dodo.com">
<group>EveryBody</group>
</item>
<item subscription="both" jid="macbook#dodo.com">
<group>EveryBody</group>
</item>
<item subscription="both" jid="123457#dodo.com">
<group>EveryBody</group>
</item>
<item subscription="both" jid="test3#dodo.com">
<group>EveryBody</group>
</item>
<item subscription="both" jid="admin#dodo.com">
<group>EveryBody</group>
</item>
<item subscription="both" jid="test4#dodo.com">
<group>EveryBody</group>
</item>
<item subscription="both" jid="yj#dodo.com">
<group>EveryBody</group>
</item>
<item subscription="both" jid="test#dodo.com">
<group>EveryBody</group>
</item>
<item subscription="both" jid="yuanjiong#dodo.com">
<group>EveryBody</group>
</item>
<item subscription="both" jid="taojiaen#dodo.com" />
<item ask="subscribe" subscription="none" jid="taojiaen#163.com" />
</query>
</iq>
SEND: <presence xmlns="jabber:client">
<status></status>
<priority>0</priority>
</presence>
RECV: <presence from="imac#dodo.com/MatriX" to="imac#dodo.com/MatriX" xmlns="jabber:client">
<status />
<priority>0</priority>
</presence>
As you can see I have lost a lot of stream because My program have not sended the right xml
please help me to find the bug.
this my code:
Config.NowXmppClient = new XmppClient();
Config.NowXmppClient.ResolveSrvRecords = false;
Config.NowXmppClient.SetXmppDomain("dodo.com");
Config.NowXmppClient.Hostname = "123.456.789s.130";
Config.NowXmppClient.Port= 5222;
const string LIC = #"eJxkkN1SgzAQhV+l470GHLXF2WZEpS2lYv+o08sIMUITAiGxwNPb2vp/s7O7
357dMwuTNKZ5RTu14HnVPyHstJIveksUveYHdIJhqmRiYu0neKFNkkpA3x2Y
GZLrVDfYBvSVw52ptBRUYQiJoNh7I9wQLRWgjxrupChI3nyCVOadoxVAnww8
QVKOK8JpdfPD2VmyGzqw3fDXoahIiKZeXaSK3u8yfG7Zl5ZjOYD+IfCreyok
1srsdh0L2Mff+gvb2uv/AFikLCfaKIq35cOwPb/yeMzasW8PMgcNuugqKpdW
MvBcq5mVt2vCellMrWw+Cdcuvy2WZIOcyaj2h342DcLQsdeBiJpX/mAHw17j
luEsImbKFs9hN2rV8Ok1HhdSsMA1o27LWW81mjxS/+V5U69UvSAoq5mTuyNn
Gyg2d8vHplHzrvZNQthyI9SgzcdP2z6gb9+A7wI=";
Matrix.License.LicenseManager.SetLicense(LIC);
Config.NowXmppClient.OnReceiveXml += new System.EventHandler<Matrix.TextEventArgs>(this.xmppClient_OnReceiveXml);
Config.NowXmppClient.OnSendXml += new System.EventHandler<Matrix.TextEventArgs>(this.xmppClient_OnSendXml);
//Config.NowXmppClient.OnStreamError += new System.EventHandler<Matrix.StreamErrorEventArgs>(this.xmppClient_OnStreamError);
Config.NowXmppClient.OnValidateCertificate += new System.EventHandler<Matrix.CertificateEventArgs>(this.xmppClient_OnValidateCertificate);
Config.NowXmppClient.OnLogin += new System.EventHandler<Matrix.EventArgs>(this.xmppClient_OnLogin);
private void xmppClient_OnValidateCertificate(object sender, CertificateEventArgs e)
{
// always accept cert
e.AcceptCertificate = true;
StackFrame[] stacks = new StackTrace().GetFrames();
Console.Write(ToString(stacks));
// or let the user validate the certificate
// ValidateCertificate(e);
}
private void xmppClient_OnLogin(object sender, Matrix.EventArgs e)
{
Console.WriteLine("OnLogin");
}
private void xmppClient_OnReceiveXml(object sender, TextEventArgs e)
{
Console.WriteLine("rec:" + e.Text);
}
private void xmppClient_OnSendXml(object sender, TextEventArgs e)
{
Console.WriteLine("send:" + e.Text);
}
anyone help!
looks like there is a problem with your TLS server certificate.
Try to install a proper server certificate or try to connect without TLS
Config.NowXmppClient.StartTls = false;

How can I add an attribute to an XML node based on another attribute?

I have the following XML:
<funds>
<fund name="A" ITEM0="7%" ITEM1="8%" ITEM2="9%" ITEM3="10%" ITEM4="11%" ITEM5="" />
<fund name="B" ITEM0="11%" ITEM1="11%" ITEM2="13%" ITEM3="14%" ITEM4="16%" ITEM5="" />
<fund name="C" ITEM0="" ITEM1="" ITEM2="" ITEM3="" ITEM4="" ITEM5="" />
<fund name="D" ITEM0="7%" ITEM1="8%" ITEM2="9%" ITEM3="10%" ITEM4="11%" ITEM5="" />
<fund name="E" ITEM0="2%" ITEM1="3%" ITEM2="3%" ITEM3="5%" ITEM4="5%" ITEM5="" />
<fund name="F" ITEM0="" ITEM1="" ITEM2="" ITEM3="" ITEM4="" ITEM5="" />
<fund name="G" ITEM0="3%" ITEM1="3%" ITEM2="3%" ITEM3="5%" ITEM4="5%" ITEM5="" />
</funds>
<ToAppend>
<append name="A" ITEM="10" />
<append name="B" ITEM="15" />
<append name="C" ITEM="20" />
<append name="D" ITEM="20" />
<append name="E" ITEM="15" />
<append name="F" ITEM="10" />
<append name="G" ITEM="10" />
</ToAppend>
How can I loop through all of the attributes in //ToAppend/append and if 'name' is a match in //funds/fund add the attribute ITEM from //ToAppend/append to //funds/fund ?
I'm trying to append the matching items to the first list but I'm not having too much luck. Trying to get this working via C# under the 2.0 framework.
Thanks in advance!
edit:
XmlNode xmlNodeInner = root.SelectSingleNode("//ToAppend/append");
XmlNode ToBeUpdated = root.SelectSingleNode("//funds/fund");
foreach (XmlElement element in ToBeUpdated)
{
Console.WriteLine(element.InnerXml);
//Match the 'name' from xmlNodeInner to the 'name' of ToBeUpdated
//if{magic occurs here and they match}
{
element.SetAttribute("ITEM6", "value from xmlNodeInner");
}
}
I just dont know how to do the comparison inquiry to determine if A=A, or even exists, since there is no guarentee on that.
Hopefully it would come out something like:
<fund name="G" ITEM0="3%" ITEM1="3%" ITEM2="3%" ITEM3="5%" ITEM4="5%" ITEM5="" ITEM6="10"/>
This seems to work:
namespace ConsoleApplication1
{
using System;
using System.Xml;
class Program
{
static void Main( string[] args )
{
const string xml = #"
<root>
<funds>
<fund name='A' ITEM0='7%' ITEM1='8%' ITEM2='9%' ITEM3='10%' ITEM4='11%' ITEM5='' />
<fund name='B' ITEM0='11%' ITEM1='11%' ITEM2='13%' ITEM3='14%' ITEM4='16%' ITEM5='' />
<fund name='C' ITEM0='' ITEM1='' ITEM2='' ITEM3='' ITEM4='' ITEM5='' />
<fund name='D' ITEM0='7%' ITEM1='8%' ITEM2='9%' ITEM3='10%' ITEM4='11%' ITEM5='' />
<fund name='E' ITEM0='2%' ITEM1='3%' ITEM2='3%' ITEM3='5%' ITEM4='5%' ITEM5='' />
<fund name='F' ITEM0='' ITEM1='' ITEM2='' ITEM3='' ITEM4='' ITEM5='' />
<fund name='G' ITEM0='3%' ITEM1='3%' ITEM2='3%' ITEM3='5%' ITEM4='5%' ITEM5='' />
</funds>
<ToAppend>
<append name='A' ITEM='10' />
<append name='B' ITEM='15' />
<append name='C' ITEM='20' />
<append name='D' ITEM='20' />
<append name='E' ITEM='15' />
<append name='F' ITEM='10' />
<append name='G' ITEM='10' />
</ToAppend>
</root>
";
// XPath that finds all "funds/fund" nodes that have a "name" attribute with the value "{0}".
const string xpathTarget = #"//funds/fund[#name='{0}']";
// XPath that finds all "ToAppend/append" nodes that have a "name" and "ITEM" attribute.
const string xpathSourceNodes = #"//ToAppend/append[#name and #ITEM]";
var doc = new XmlDocument();
doc.LoadXml( xml );
foreach ( XmlNode sourceNode in doc.SelectNodes( xpathSourceNodes ) )
{
string name = sourceNode.Attributes[ "name" ].Value;
string item = sourceNode.Attributes[ "ITEM" ].Value;
XmlNode targetNode = doc.SelectSingleNode( String.Format( xpathTarget, name ) );
if ( null != targetNode )
{
XmlAttribute newAttribute = doc.CreateAttribute( "ITEM6" );
newAttribute.Value = item;
targetNode.Attributes.Append( newAttribute );
}
}
}
}
}

Categories

Resources